Effects and synchronisation · mid
Stale closures in effects, timers and callbacks
Every render creates new functions that "see" that render's props and state; a callback kept from an old render (an interval started with [], a debounced handler) keeps reading old values, which is a stale closure.
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceThe notes
What you must know
useEffect(() => { const id = setInterval(() => setCount(count + 1), 1000); return () => clearInterval(id); }, [])shows 1 forever: the interval callback closed overcount = 0.- Fix 1: updater form
setCount(c => c + 1); React gives the latest value. - Fix 2: keep the latest value or callback in a ref (
savedCallback.current = callbackafter render) and call the ref inside the interval; this is the classicuseIntervalhook. - Fix 3 (React 19.2+): move the "event" logic into
useEffectEvent; it always sees the latest props and state and is not a dependency. - Adding
countto deps works but clears and recreates the interval every tick, which drifts and resets timing. - Same bug with debounce/throttle: a debounced function created once keeps the first render's values; created on every render, it loses its timer. Store it in a ref or memo and read latest values through a ref.
- Stale closures are plain JavaScript closures plus React's per-render snapshots; nothing is "wrong" with React.
The red pen
Common traps: mistake → fix
Mistake: "Disable exhaustive-deps and it works"
Fix: it hides exactly this bug.
Mistake: "Recreating
setIntervalon every render is fine"Fix: it drifts and leaks if cleanup is missed.
Mistake: "A ref fixes everything"
Fix: refs are not reactive; the screen will not update from a ref change.
Easy to hard
Questions interviewers ask, easy to hard
- What does this timer display after 5 seconds? Fix it three different ways.
- Why is "add
countto the deps" a weak fix? - Write a
useInterval(callback, delay)hook. - How does
useEffectEventhelp here? - Does the same bug appear with a debounced search handler?
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceYour first interview is free
Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.