Skip to content

Instantly share code, notes, and snippets.

@timrach
Last active April 5, 2020 14:10
Show Gist options
  • Save timrach/d14d8064bc427c2e1445be54e13d0ee4 to your computer and use it in GitHub Desktop.
Save timrach/d14d8064bc427c2e1445be54e13d0ee4 to your computer and use it in GitHub Desktop.
// 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