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:
- Need to persist across renders
- Can be mutated without triggering a re-render
- 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.