Course contentsShow
← React
Lesson 707 of 2,39619. useRefFree lesson

Common Use Case: Counters and Flags

Store values like request IDs, animation frame IDs, or boolean flags that change frequently but don't affect UI.

Common Use Case: Counters and Flags

You'll learn how to use useRef to store non-visual data that changes frequently without triggering re-renders.

The Problem with State for Everything

Sometimes you need to track values that change often but don't affect what the user sees. Classic examples include:

  • Request IDs for tracking which API call is the latest
  • Animation frame IDs from requestAnimationFrame
  • Boolean flags like "is component mounted?" or "has user interacted?"

If you used useState for these, you'd trigger unnecessary re-renders every time they change. That's wasteful when the UI doesn't need updating.

When to Reach for useRef

Use useRef for values that:

  1. Need to persist across renders
  2. Can be mutated without triggering a re-render
  3. Don't directly affect what's displayed

Think of it like a sticky note on the side of your component — you can write on it, check it, change it anytime, but changing it doesn't make React re-paint the screen.

Common Patterns

Request counter to prevent race conditions:

const requestIdRef = useRef(0);

function fetchData() {
  const requestId = ++requestIdRef.current;
  // Later: if (requestId !== requestIdRef.current) return; // stale
}

Animation frame ID for cleanup:

const frameIdRef = useRef(null);

useEffect(() => {
  frameIdRef.current = requestAnimationFrame(animate);
  return () => cancelAnimationFrame(frameIdRef.current);
}, []);

Mounted flag to avoid setting state after unmount:

const isMountedRef = useRef(true);

useEffect(() => {
  return () => { isMountedRef.current = false; };
}, []);

Key Takeaway: Use useRef for counters, IDs, and flags that track internal logic but don't need to trigger renders — they're tracking mechanisms, not display data.