Intermediate LevelReact JS & React 19
What causes stale closures in React hooks and how do you resolve them?
❓ Interview Prompt: Explain JavaScript Closures, stale closure traps in `useEffect`/`useCallback`, omitted dependency array items, and functional updaters.
A Stale Closure occurs when a function or callback inside 'useEffect', 'useCallback', or 'setTimeout' captures variables from an earlier render pass, retaining outdated "stale" state values:
Common Cause:
Forgetting to list dynamic variables in the hook's dependency array!
Fixes:
1
Include all referenced state/props in the dependency array.
2
Use functional updater syntax ('setCount(prev => prev + 1)') so the setter does not depend on closed-over state variables.
Code Implementation Example
jsx
function StaleTimer() {
const [count, setCount] = useState(0);
useEffect(() => {
const timer = setInterval(() => {
// ❌ STALE CLOSURE: 'count' is captured as 0 forever!
// setCount(count + 1);
// ✅ FIX: Functional updater uses current state value
setCount(prev => prev + 1);
}, 1000);
return () => clearInterval(timer);
}, []); // Empty deps okay with functional updater!
}💡Resolving stale closure bugs in setInterval using functional state updaters.
🎯 Interview Key Takeaway
Fix stale closures by including referenced variables in dependency arrays or using functional state updaters.
#Stale Closures#Closures#useEffect#Hooks#Intermediate
Back to all React JS & React 19 Questions→