← Back to React, page 6

react-0104 · Easy fresher

When should you use a ref instead of state, and what happens to the screen when each one changes?

Use state for anything that appears on screen, because changing state re-renders the component. Use a ref for values that must survive re-renders but do not affect what is rendered, such as timer ids, DOM nodes, or the previous value. Changing ref.current does not cause a re-render, and it should not be read or written during render. If changing a value should update the screen, it belongs in state.

Full answer

Both state and refs persist across re-renders, which is why they are easy to confuse. The difference is what a change does.

State. setCount(1) tells React that the output may have changed, so React re-renders the component with the new value. State is treated as a snapshot for each render, and must be updated through the setter. Use it for anything the user sees or any value that decides what is rendered.

Refs. useRef(0) returns an object { current: 0 } that is the same object on every render. Assigning ref.current = 5 changes the object but does not notify React, so nothing re-renders. Good uses:

  • Holding a DOM node: <input ref={inputRef} /> and then inputRef.current.focus().
  • Storing an id that must be cleared later (setTimeout, setInterval, subscriptions).
  • Remembering a value between renders without displaying it (previous props, a render counter for debugging, a mutable flag such as "is mounted").

Rules. Do not read or write ref.current during rendering, except for the one-time lazy initialization, because render must stay pure and React cannot track the change. Read and write refs in event handlers and effects. If you catch yourself showing a ref value in JSX, you probably want state.

A useful test: "If this value changes, must the screen change?" Yes means state. No means a ref may be right. Another point: a ref update is immediate and synchronous, while a state update is applied on the next render, which makes a ref handy inside callbacks that need the latest value. Be careful, because it also avoids React's change tracking, so bugs are harder to find.

The example changes a ref and then state and logs what each render sees.

jsx
import { useRef, useState } from 'react';

export default function Counters() {
  const [stateCount, setStateCount] = useState(0);
  const refCount = useRef(0);

  console.log('render: state=' + stateCount + ', ref=' + refCount.current);

  return (
    <div>
      <button onClick={() => (refCount.current += 1)}>Ref +1</button>
      <button onClick={() => setStateCount(stateCount + 1)}>State +1</button>
      <p>State: {stateCount}</p>
    </div>
  );
}

The log reads the ref during render only to show the effect for teaching. Real components should not do that. The first click changed the ref and caused no render. The second click changed state, and the new render then saw both values. Output of the run: render: state=0, ref=0 render: state=1, ref=1

Key points

  • State changes cause re-renders. Ref changes do not.
  • Use state for what is displayed. Use refs for DOM nodes, timer ids and non-visual values.
  • Do not read or write ref.current while rendering.
  • If a ref value shows up in JSX, it probably should be state.
  • Refs update immediately. State updates apply on the next render.

Common mistakes

  • Storing displayed values in a ref and wondering why the screen does not update.
  • Reading or writing ref.current during rendering.
  • Using state for timer ids and causing extra renders.
  • Using a ref to avoid fixing a stale closure that should be solved with proper dependencies.
  • Mutating state objects instead of using the setter.

Follow-ups

  • How do you keep the previous value of a prop with a ref?
  • Why can a ref be safer than state inside a timer callback, and what is the risk?
  • Can a ref hold a DOM node and a value at the same time?

Tips

  • Give the screen test: "must the screen change?".
  • Name three non-visual uses of refs.
  • Mention the render-purity rule.