Sphere
Log in Join
☆ 6

setInterval callback reads stale state every tick

React 17.0.2, plain CRA. I set up a setInterval(() => setCount(count + 1), 1000) inside a useEffect with []. count never goes past 1. I know the empty deps is the problem but if I add [count] the interval keeps getting torn down and recreated and it fires weird. What's the actual fix here without pulling in some library?

⚑ Report

3 replies

☆ 3
R rabbit ·2026-10-18#1

use the functional updater: setCount(c => c + 1). Then you don't need count in the deps at all and the interval stays stable. That's basically the whole trick. The callback always gets the latest value.

⚑ Report
☆ 0
B bash ·2026-10-24#2

that worked, can't believe I didn't try it. one more thing, the cleanup — I'm doing clearInterval in the return of the effect, right? I had it in there but want to make sure I'm not leaking intervals when the component unmounts.

⚑ Report
☆ 0
F ferret ·2026-10-25#3

yep, return () => clearInterval(id). Without it you'll get duplicate intervals under StrictMode in React 18 because effects mount twice in dev. Not so much in 17 but still a good habit to keep.

⚑ Report
Log in to reply.