In the documentation for useEffect()
it shows the following example:
function Example() {
const [count, setCount] = useState(0);
useEffect(() => {
document.title = `You clicked ${count} times`;
});
}
It then says:
Experienced JavaScript developers might notice that the function passed to
useEffect
is going to be different on every render. This is intentional. In fact, this is what lets us read thecount
value from inside the effect without worrying about it getting stale. Every time we re-render, we schedule a different effect, replacing the previous one.
I don't understand why count
would get stale inside useEffect()
since useEffect
has count
within its closure. Since useEffect()
is a hook, shouldn't it always have access to the latest state variable? Also, in general, how can I be sure that I always have the latest value for a state variable?