Digiaru

Digiaru started this conversation 3 months ago.

Stale Closure in useEffect or Timer Causes Incorrect State Updates

I set up an interval inside useEffect to update a counter, but the counter remains static (always zero). Why?

Kar

Posted 3 months ago

Because the interval callback closes over the initial state (count = 0) and never sees updates, causing stale closures ([turn0search2]). Fix: jsx Copy code useEffect(() => { const id = setInterval(() => { setCount(prev => prev + 1); }, 1000); return () => clearInterval(id); }, []); Use functional updates (prev => prev + 1) to avoid closure over stale state.