Using useRef to Break the Loop
What you'll learn: How to use useRef to track values without triggering effect re-runs, breaking infinite loops.
The Core Problem
Sometimes you need to access the latest value of something inside an effect, but adding it to the dependency array causes an infinite loop. Classic example: you need the current value of count inside an effect, but count changes every render and triggers the effect again.
Why useRef Solves This
Refs are mutable containers that persist between renders but don't trigger re-renders when changed. Think of a ref as a box sitting off to the side: you can peek inside or update what's in it anytime, and React doesn't care. It won't re-run your effect.
The Pattern
function Timer() {
const [count, setCount] = useState(0);
const countRef = useRef(count);
// Keep ref in sync with state
countRef.current = count;
useEffect(() => {
const id = setInterval(() => {
// Access latest count without adding it to dependencies
console.log('Current count:', countRef.current);
}, 1000);
return () => clearInterval(id);
}, []); // Empty array: effect runs once
return <button onClick={() => setCount(c => c + 1)}>{count}</button>;
}
The Strategy
- Store the value in a ref:
countRef.current = count(do this in the render body) - Use
countRef.currentinside the effect - Don't add the ref to dependencies (refs never trigger re-runs)
- The effect runs once, but always reads the fresh value
This breaks the loop because the ref acts as a "live wire" to the latest value without participating in React's dependency tracking.
Key Takeaway: Use useRef to access fresh values inside effects without adding them to the dependency array, preventing infinite loops while maintaining access to current data.