useRef and mutable values

Intermediate · 10 min

Using useRef for a mutable value that persists across renders without triggering a re-render — timer ids, previous-value tracking, render counters.

Before thisThe rules of hooksuseEffect and synchronizing with external systems

Web Dev Simplified · 10 min

useRef and mutable values

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by Web Dev SimplifiedReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • useRef returns a plain mutable object with a single property, current, that keeps its value across re-renders without React tracking it as state.
  • Changing ref.current never triggers a re-render, which is the whole point: it's for values a component needs to remember without those values affecting what's on screen.
  • state is for anything the render output depends on; a ref is for anything a component needs to remember that the render output does not depend on, such as a timer id, an interval id, or a previous value for comparison.
  • A common pattern is storing the previous render's value in a ref inside an effect, so you can compare the current value against it on the next render.
  • Reading or writing ref.current during rendering itself is unsafe — refs are meant to be read and written inside event handlers and effects, not in the function body that computes JSX.
  • A ref persists for the component instance's entire lifetime: it survives every re-render and is only reset when the component unmounts and a new instance is created.

A box that doesn’t trigger a re-render

useState and useRef look similar at first glance — both let a component hold onto a value across renders — but they behave completely differently when that value changes:

function Example() {
  const [count, setCount] = useState(0); // changing this re-renders
  const countRef = useRef(0);            // changing this does not

  function handleClick() {
    setCount(count + 1);      // schedules a re-render
    countRef.current += 1;    // just mutates an object, nothing else happens
  }

  return <button onClick={handleClick}>{count}</button>;
}

useRef(initialValue) returns a plain JavaScript object shaped like { current: initialValue }. React creates that object once, on the first render, and hands back the exact same object on every later render of that component — it never replaces it and never re-renders because you mutated .current. That makes a ref the right tool whenever you need a value to survive across renders, but the UI doesn’t need to reflect it.

Timer ids are the canonical example

A setInterval or setTimeout call returns an id you need later, purely to cancel it — the id itself never appears on screen:

function Stopwatch() {
  const [seconds, setSeconds] = useState(0);
  const intervalRef = useRef(null);

  function start() {
    intervalRef.current = setInterval(() => {
      setSeconds((s) => s + 1);
    }, 1000);
  }

  function stop() {
    clearInterval(intervalRef.current);
  }

  return (
    <div>
      <p>{seconds}s</p>
      <button onClick={start}>Start</button>
      <button onClick={stop}>Stop</button>
    </div>
  );
}

If intervalRef were useState instead, every start() call would trigger an extra, pointless re-render just to store a number nobody displays. Using a ref makes the intent explicit: this value exists for bookkeeping, not for rendering.

Tracking the previous value

A frequent pattern: knowing what a prop or piece of state was on the last render, so you can compare it to what it is now.

function usePrevious(value) {
  const ref = useRef(undefined);

  useEffect(() => {
    ref.current = value; // runs after render, so this still holds "last render's value" during the render itself
  });

  return ref.current;
}

function TemperatureDisplay({ temperature }) {
  const previousTemperature = usePrevious(temperature);

  const direction =
    previousTemperature === undefined
      ? "—"
      : temperature > previousTemperature
        ? "↑ rising"
        : temperature < previousTemperature
          ? "↓ falling"
          : "→ steady";

  return (
    <p>
      {temperature}° {direction}
    </p>
  );
}

The trick here is timing: the useEffect runs after the DOM has been updated for the current render, so during that current render, ref.current still holds whatever was written during the previous render’s effect. By the time the effect for this render runs and overwrites ref.current, the component has already used the old value in its JSX. This small custom hook, usePrevious, is common enough that you’ll recognize the pattern elsewhere once you’ve written it once.

A render counter, for debugging

Refs are also handy for instrumentation that shouldn’t itself cause more renders:

function ExpensiveList({ items }) {
  const renderCount = useRef(0);
  renderCount.current += 1;

  console.log(`ExpensiveList has rendered ${renderCount.current} times`);

  return (
    <ul>
      {items.map((item) => (
        <li key={item.id}>{item.name}</li>
      ))}
    </ul>
  );
}

Mutating renderCount.current directly in the function body is acceptable here specifically because it’s read-only instrumentation with no effect on what’s rendered — it never drives JSX output and never needs to be consistent under Strict Mode’s double-invoked renders. As a habit, though, prefer doing ref writes inside effects or event handlers; reserve body-level mutation for cases exactly like this one, where you understand why it’s safe.

state vs. ref, as a rule of thumb

If changing the value should make the screen look different, it’s state. If the component just needs to remember it internally — across renders, without caring whether the screen updates — it’s a ref. Mixing the two up in either direction causes real problems: using state for a timer id causes extra re-renders for no visual benefit; using a ref for something that should appear on screen means the UI silently never updates when it changes, because nothing told React to re-render.

What the video covers

Web Dev Simplified’s video is a focused explainer of useRef as a mutable container that survives re-renders without causing them, covering timer ids and previous-value tracking — the exact core of this lesson. It’s a reliable, concise reference for the mechanics from a well-established React education channel; the render-counter example and the state-vs-ref framing above extend a bit further than the video goes.

Where this fits

useRef’s other major use — attaching it directly to a DOM element instead of just holding an arbitrary value — is common enough, and has enough of its own rules, to deserve its own lesson: direct DOM access with refs.

Check yourself

  1. 01What does changing a ref's current property do to the component that owns it?

    Nothing by itself — React does not re-render a component because a ref's current property changed, which is exactly why refs are the right tool for values that need to persist without affecting what's rendered.

  2. 02When should you reach for useRef instead of useState?

    When the value needs to survive across renders but the component's rendered output doesn't depend on it — a setInterval id you'll need later to clear it, or a flag that tracks something happened, are both good fits for a ref rather than state.

  3. 03How can a ref be used to track a component's previous value?

    By storing the current value into a ref inside a useEffect that runs after every render, so that on the next render the ref still holds the value from the render before — letting the component compare 'now' against 'last time'.

  4. 04Why is it unsafe to read or write ref.current directly in a component's function body during render?

    Because render should be a pure calculation of what to display, and mutating a ref there happens on every render pass — including ones React discards or re-runs for reasons like Strict Mode — so a read or write that affects behavior belongs in an effect or event handler instead.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark