Course contentsShow
← React
Lesson 632 of 2,39617. Common useEffect MistakesFree lesson

Using useRef to Break the Loop

Strategic use of refs to track values without triggering effect re-runs when appropriate.

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

  1. Store the value in a ref: countRef.current = count (do this in the render body)
  2. Use countRef.current inside the effect
  3. Don't add the ref to dependencies (refs never trigger re-runs)
  4. 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.