Course contentsShow
← React
Lesson 398 of 2,39611. useState Patterns and PitfallsFree lesson

useRef for Mutable Current Values

Storing latest state in a ref to access current values in async code without triggering re-renders.

useRef for Mutable Current Values

What you'll learn: How to use useRef to store the latest state value in async code without causing extra re-renders.

The Problem with Stale State in Async Code

You've seen how closures can trap old state values in setTimeout, setInterval, and event listeners. The functional update pattern (setState(prev => ...)) solves this when you're updating state based on its previous value. But what if you just need to read the latest state without updating it?

function Timer() {
  const [count, setCount] = useState(0);

  useEffect(() => {
    const id = setInterval(() => {
      console.log(count); // Always logs 0! Stale closure.
    }, 1000);
    return () => clearInterval(id);
  }, []); // Empty deps means count is "frozen" at 0

  return <button onClick={() => setCount(c => c + 1)}>{count}</button>;
}

The useRef Solution

A ref is like a box that holds a mutable value in its .current property. Unlike state, changing ref.current doesn't trigger a re-render. It's perfect for storing the "latest" version of a value for async code to read:

function Timer() {
  const [count, setCount] = useState(0);
  const countRef = useRef(count);

  // Keep ref in sync with state
  useEffect(() => {
    countRef.current = count;
  });

  useEffect(() => {
    const id = setInterval(() => {
      console.log(countRef.current); // Always reads latest!
    }, 1000);
    return () => clearInterval(id);
  }, []);

  return <button onClick={() => setCount(c => c + 1)}>{count}</button>;
}

Now the interval can peek at the current count without being trapped by a stale closure.

Key Takeaway: Use useRef to create a mutable container (.current) that persists across renders and updates without triggering re-renders—perfect for letting async code access fresh values.