Common Use Case: Avoiding Stale Closures
What you'll learn: How to use useRef to ensure async code and intervals always see the latest values, avoiding the stale closure trap.
The Stale Closure Problem with Async Code
Remember the classic stale closure bug? It gets worse with timers and async operations. When you set up a setTimeout or setInterval, they capture the values that existed when they were created. If those values change, your callback doesn't know:
function Counter() {
const [count, setCount] = useState(0);
useEffect(() => {
const intervalId = setInterval(() => {
// This always logs 0! It captured count from initial render
console.log(count);
}, 1000);
return () => clearInterval(intervalId);
}, []); // Empty array means this closure is "frozen in time"
return <button onClick={() => setCount(count + 1)}>Count: {count}</button>;
}
The useRef Solution
Store the value in a ref. Since ref.current is always the same mutable container, async code can read from it and always get the latest value:
function Counter() {
const [count, setCount] = useState(0);
const countRef = useRef(count);
// Keep ref in sync with state
countRef.current = count;
useEffect(() => {
const intervalId = setInterval(() => {
// Now this always logs the current count!
console.log(countRef.current);
}, 1000);
return () => clearInterval(intervalId);
}, []); // Still empty, but now we access fresh values
return <button onClick={() => setCount(count + 1)}>Count: {count}</button>;
}
Think of the ref as a "window" your interval keeps looking through—the view always shows what's current, even though the interval itself hasn't changed.
This pattern works for API callbacks, WebSocket handlers, and any async code that shouldn't recreate subscriptions on every value change.
Key Takeaway: Use useRef to store values that async operations need to read—update the ref during render, and your callbacks will always see the latest version without re-subscribing.