How to Fix React Captured Value in Closures
In this fix, you'll learn why React closures capture the value at render time causing stale reads in setTimeout or event handlers, why this matters for real-time chat apps, and how this pattern affects live polling features.
JavaScript closures capture the value of variables at the time the closure is created. In React, each render creates a new closure with the current state value frozen at that render.
The Problem
The following code demonstrates the typical mistake:
function Timer() {
const [count, setCount] = useState(0);
useEffect(() => {
setInterval(() => {
setCount(count + 1); // count is always 0
}, 1000);
}, []);
return <p>{count}</p>;
}
// count stays at 1 — captured value is always 0 from the first render
The Fix
Here is the corrected version:
function Timer() {
const [count, setCount] = useState(0);
useEffect(() => {
const id = setInterval(() => {
setCount(c => c + 1); // functional updater
}, 1000);
return () => clearInterval(id);
}, []);
return <p>{count}</p>;
}
// count increments by 1 every second correctly
Prevention
- Always use functional updates (prev => prev + 1) when reading previous state inside closures.
- Add all dependencies to useEffect/useCallback dependency arrays to recreate the closure.
- Use useRef to store the latest callback without causing re-renders.
- For real-time data, use libraries like React Query that manage staleness externally.
- Consider using useEvent (React 19) for stable callback identity.
Common Mistakes with capture value
- Non-exhaustive pattern matches that compile with warnings then crash at runtime
- Misunderstanding that
Stringis[Char]with poor performance for large text operations - Using
foldlinstead offoldl'causing stack overflow on large lists
These mistakes appear frequently in real-world REACT code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro