Debugging Stale State with Logging
What you'll learn: How to use strategic logging to identify and diagnose stale closure bugs in your React components.
When stale state bites you, it's often invisible—your code looks correct, but it's capturing old values. The solution? Add timestamps and state snapshots to make the invisible visible.
The Logging Strategy
Add console.log statements at two critical points:
- When the closure is created (component render)
- When the closure executes (inside the callback)
Log both the current state value and a timestamp or render ID:
function Timer() {
const [count, setCount] = useState(0);
const renderTime = Date.now(); // Capture when this render happened
useEffect(() => {
console.log(`Creating interval at render ${renderTime}, count is ${count}`);
const id = setInterval(() => {
console.log(`Interval firing! Captured count from render ${renderTime}: ${count}`);
setCount(count + 1); // BUG: stale closure
}, 1000);
return () => clearInterval(id);
}, []); // Empty deps = closure captures initial count forever
return <div>{count}</div>;
}
What the Logs Reveal
You'll see output like:
Creating interval at render 1625000000000, count is 0
Interval firing! Captured count from render 1625000000000: 0
Interval firing! Captured count from render 1625000000000: 0
Interval firing! Captured count from render 1625000000000: 0
The render timestamp never changes in the callbacks, proving the callback is still referencing the original closure—even though the component has re-rendered with new count values.
The Fix Verification
Change to setCount(prev => prev + 1) and you'll see the callback still references the old render, but now it doesn't matter—it uses the current state from React's internals, not the stale closure variable.
Key Takeaway: Logging render timestamps alongside state values exposes stale closures by showing which "version" of your component a callback is executing from.