Last active
April 5, 2020 14:10
-
-
Save timrach/d14d8064bc427c2e1445be54e13d0ee4 to your computer and use it in GitHub Desktop.
This file contains 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
// From https://reactjs.org/docs/hooks-faq.html#what-can-i-do-if-my-effect-dependencies-change-too-often | |
function Counter() { | |
const [count, setCount] = useState(0); | |
useEffect(() => { | |
const id = setInterval(() => { | |
setCount(count + 1); // This effect depends on the `count` state | |
}, 1000); | |
return () => clearInterval(id); | |
}, []); // 🔴 Bug: `count` is not specified as a dependency | |
return <h1>{count}</h1>; | |
} | |
function Counter() { | |
const [count, setCount] = useState(0); | |
useEffect(() => { | |
const id = setInterval(() => { | |
setCount(c => c + 1); // ✅ This doesn't depend on `count` variable outside | |
}, 1000); | |
return () => clearInterval(id); | |
}, []); // ✅ Our effect doesn't use any variables in the component scope | |
return <h1>{count}</h1>; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment