Refs: remembering without rendering

Intermediate

Introduction

State has one job: when it changes, the page updates. Sometimes a component needs to remember something that should not update the page: the id of a running timer, the number of times something happened, or the input element to put the cursor in. For these, React gives you refs, a way to remember a value without rendering, and to reach real DOM elements when you need to.

How it works

useRef(initial) returns an object with one property, current, set to the initial value. React gives the component the same object on every render, so whatever you store in current survives, but changing it does not make React render:

const clicks = useRef(0);
function handleClick() {
  clicks.current += 1; // remembered, but the page does not change
}

That makes refs right for values that only event handlers and effects use: a timer id to clear later, the previous value of something, a flag saying a request is already in progress.

The other use is a DOM ref. Pass a ref to an element's ref attribute, and React sets current to the DOM element once it exists:

const inputRef = useRef(null);
<input ref={inputRef} />
<button onClick={() => inputRef.current.focus()}>Focus</button>

Some things can only be done on the DOM element itself: moving focus, selecting text, scrolling an element into view, measuring its size, or playing a video. Refs are React's escape hatch for them.

Two rules keep refs safe. Do not read or write current during rendering (except to set it up once), because rendering must give the same result every time; use refs in event handlers and effects. And do not use a ref for anything that appears on the page: if the page should change when the value changes, it must be state. A good test is to ask "does the JSX use this value?": if yes, it is state.

Example

App.jsx
console.log output from the page shows here.

Line by line

  1. inputRef starts as null and becomes the input element after the first render.
  2. "Focus the input" calls the DOM element's own focus method.
  3. "Count quietly" adds to clicks.current; nothing on the page changes.
  4. "Show the count" copies the ref's value into state, which renders it.

Expected result

The preview shows an input, three buttons and "Last shown: 0". "Focus the input" puts the cursor in the field. Pressing "Count quietly" three times changes nothing visible; "Show the count" then shows "Last shown: 3".

In the real world

Search pages focus the search box when they open, chat apps scroll to the newest message, forms move focus to the first field with an error, and video players call play and pause on the video element, all through refs. Integrations with libraries that manage their own DOM, such as maps and charts, give the library a DOM element through a ref.

Common mistakes

  • Storing something shown on the page in a ref, so the page does not update when it changes.
  • Reading inputRef.current during render, when it may still be null.
  • Using refs to change the DOM in ways React also controls, such as adding and removing children.
  • Creating a ref with useRef inside a loop or condition, which breaks the rules of Hooks.

Best practices

  • Prefer state and props; reach for refs only for focus, measurement, media and non-visual values.
  • Read and write refs in event handlers and effects.
  • Give refs clear names ending in Ref when they hold DOM elements, such as inputRef.

Summary

useRef gives a component a box, current, that survives renders without causing them. Passed to an element's ref attribute, it holds the DOM element, which allows focusing, scrolling and measuring. Use refs for values the page does not show and for DOM access, and state for everything that should appear on the page.

Quick check

1. What happens when you change ref.current?
2. How do you get the DOM element of an input?
3. Which value belongs in a ref rather than state?
4. When may you read a DOM ref's current?

Key takeaways

  • useRef gives a box whose current value survives renders; changing it does not render.
  • Pass a ref to an element's ref attribute to reach the DOM node, for example to focus it.
  • Use state for anything shown on the page, and refs for values only event handlers and effects need.

Practice problems for this lesson

My notes

Write down what you want to remember from this lesson. Notes are saved on this device as you type, and appear on your dashboard.