How do you fix a stale closure in React?
Use the functional form of setState (setCount(c => c + 1)) which receives the latest state. Or add the state to the useEffect dependency array. Or use useRef to hold the latest value. Or use useReducer (dispatch is stable).
Verify This Answer
Cross-check this information using these trusted sources:
More FAQs in Closures and React: Stale Closures Explained
A callback (in useEffect, setInterval, etc.) that captures state from a previous render, not the current one. When the state updates in later renders, the old callback still sees the old value, causing bugs.
Because the setInterval callback closes over count from the render when useEffect ran (usually the first render, count = 0). Each tick calls setCount(0 + 1), so count stays at 1. Use setCount(c => c + 1) instead.
A ref holds a mutable .current property that persists across renders. Update countRef.current = count on each render. The interval reads countRef.current, which always has the latest value, avoiding the stale closure.
Still have questions?
Browse all our FAQs or reach out to our support team
