This code is from react document:
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>;
}
And they said that:
The empty set of dependencies, [], means that the effect will only run once when the component mounts, and not on every re-render. The problem is that inside the setInterval callback, the value of count does not change, because we’ve created a closure with the value of count set to 0 as it was when the effect callback ran. Every second, this callback then calls setCount(0 + 1), so the count never goes above 1.
But isn't the function in setInterval is closure so its count variable reference to count state of Counter, when setCount run Count will change and so function in setInterval must be able to get new value of count? Am i missing something?