Q42: What is a Stale Closure in React Hooks and how do you resolve it?

A Stale Closure occurs when a closure function (like a useEffect or useCallback) captures state or prop variables from an earlier render pass and continues referencing those outdated values over time. Resolved by declaring dependencies accurately or using state updater callbacks.

Stale Closure Fix
// ❌ STALE CLOSURE: Captured initial count=0 continuously
useEffect(() => {
  const id = setInterval(() => setCount(count + 1), 1000);
  return () => clearInterval(id);
}, []); // Missing count dependency!

// ✅ FIX: Functional state update reads latest queue state
useEffect(() => {
  const id = setInterval(() => setCount(prev => prev + 1), 1000);
  return () => clearInterval(id);
}, []);
💡 Functional updates eliminate reliance on closure-captured state variables inside interval timers.
Key Takeaways
  • Functions capture variables from the specific render cycle in which they were created.
  • Fix by listing dependencies correctly or using functional state updaters (setVal(v => v + 1)).
Knowledge Check

What is the cause of a stale closure inside a useEffect callback?