How to Fix Stale Closure in useCallback
DodaTech
Updated 2026-06-26
1 min read
The Problem
In this quick-fix, you'll learn how to avoid stale closures when using useCallback. This matters because stale closures capture old state values causing bugs. In real-world applications, this pattern appears in interval callbacks event handlers async operations.
The Wrong Way
function Timer() {
const [count, setCount] = useState(0);
useEffect(() => {
const id = setInterval(() => { console.log(count); }, 1000);
return () => clearInterval(id);
}, []);
return <div>{count}</div>;
}
Console always shows 0 even when count changes stale closure
The Right Way
function Timer() {
const [count, setCount] = useState(0);
useEffect(() => {
const id = setInterval(() => { console.log(count); }, 1000);
return () => clearInterval(id);
}, [count]);
return <div>{count}</div>;
}
Console shows latest count effect re-runs when count changes
Prevention
- Include all values used in callback in deps array
- Use functional updates to avoid stale state
- Use refs for values read inside callbacks
FAQ
This guide is brought to you by DodaTech -- built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro