Created
August 26, 2020 23:23
-
-
Save LevPewPew/0c5c1842ee3f430777d9322eea09e024 to your computer and use it in GitHub Desktop.
a better way of running conditional useEffect hooks
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // 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