The useRef Escape Hatch for Current Values
What you'll learn: How to use useRef to access the latest values inside stable callbacks without triggering unnecessary re-renders or adding problematic dependencies.
The Problem with Stable Callbacks
You've learned to use useCallback to keep function references stable for React.memo children. But there's a tension: the callback needs to be stable (minimal dependencies), yet it also needs to access current values from props or state. Adding those values to the dependency array recreates the callback, defeating the purpose of memoization.
The useRef Solution
useRef gives you a mutable container that persists across renders but doesn't trigger re-renders when changed. Think of it as a "box" that always exists at the same memory address, even though you can change what's inside.
const latestValueRef = useRef(value);
// Update it in render (or useEffect)
latestValueRef.current = value;
const stableCallback = useCallback(() => {
// Access the latest value without adding it as a dependency
console.log(latestValueRef.current);
}, []); // Empty array: truly stable
How It Works
Every render, you update latestValueRef.current with the latest value. Your useCallback has zero dependencies (stable forever), but when it executes, it reads from latestValueRef.current, which always holds the current value. The ref itself never changes identity, so no dependency violation occurs.
When to Use This Pattern
This is your "escape hatch" when functional updates aren't enough and you need access to props/context inside a callback that must remain stable. Common in event handlers, intervals, or callbacks passed to memoized components.
Key Takeaway: Store the latest value in a ref and access ref.current inside stable callbacks to break the dependency cycle without sacrificing correctness.