Skip to content

Instantly share code, notes, and snippets.

@LevPewPew
Created August 26, 2020 23:23
Show Gist options
  • Select an option

  • Save LevPewPew/0c5c1842ee3f430777d9322eea09e024 to your computer and use it in GitHub Desktop.

Select an option

Save LevPewPew/0c5c1842ee3f430777d9322eea09e024 to your computer and use it in GitHub Desktop.
a better way of running conditional useEffect hooks
// return first, instead of wrapping the task itself in an if condition.
// this is better because it prevents the clearTimeout being run
function App() {
const [varA, setVarA] = useState(0);
useEffect(() => {
if (varA >= 5) return;
const timeout = setTimeout(() => setVarA(varA + 1), 1000);
return () => clearTimeout(timeout);
}, [varA]);
return <span>Var A: {varA}</span>;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment