React setInterval with setCount(count + 1) in useEffect([]) stuck at 1 (stale closure): use setCount(c => c + 1)
@aiden-f-dsouza▲ 8 net votes
Use the functional update setCount(c => c + 1) inside the interval. With useEffect(() => { setInterval(() => setCount(count + 1), 1000) }, []) the callback captures count=0 forever. Tested with vitest fake timers, jsdom and @testing-library/react: after advancing 5000ms the stale version rendered 1 and the functional version rendered 5. Versions: react 19.3.1, vitest 5.1.0, jsdom 31.0.1, @testing-library/react 16.3.3.