Skip to content
Tutorials Center
My learning

Topics

Lesson 31 of 132 ยท Hooks

Refs with useRef

Learn useRef in React 19 - mutable values that survive renders, DOM refs for focus and scrolling, refs versus state, callback refs with cleanup, and passing ref as a prop without forwardRef.

State is the right place for anything that appears on screen: when it changes, React renders again. But some information does not belong on screen. The id of a running timer, the previous value of a prop, the <input> element you want to focus: React needs to remember them between renders, yet changing them should not trigger a render. For that, React gives you refs.

A ref is a box with a single slot called current. React promises to give you the same box on every render of the same component instance, and to leave whatever you put in the slot alone. This lesson covers the two jobs of refs, storing mutable values and reaching DOM elements, the rules for using them safely, and the React 19 changes: ref callbacks with cleanup, and ref as a normal prop.

Creating a ref

useRef(initialValue) returns an object { current: initialValue }. The same object is returned every time the component renders.

JSX
import { useRef } from 'react';

const countRef = useRef(0);
countRef.current = countRef.current + 1; // allowed, but not during render (see below)

Two properties make a ref different from state:

useState useRef
Returns [value, setValue] { current }
Changing it Call the setter: schedules a render Assign to current: nothing happens
Reading during render Safe, it is a snapshot Not safe: it may change without React knowing
Survives re-renders Yes Yes

A ref is plain JavaScript. Writing ref.current = 5 is just an assignment, so React does not know it happened.

Job 1: remembering something without re-rendering

The classic example is a timer id. You need it later to stop the timer, but the id has nothing to do with what the screen shows. If it lived in a plain let variable inside the component, a re-render would create a fresh variable and you would lose the id. If it lived in state, setting it would cause a needless render. A ref is exactly right.

A timer id stored in a ref

Press Start, then press Start again straight away: the console shows start and then already running, because the second click found the id in intervalRef.current even though the component has re-rendered several times in between. Press Stop and the renders stop. (The exact number of ticks depends on timing, so the label only describes it roughly.)

Notice what writing to intervalRef.current did not do: it did not render. Only setTicks did.

What else is a good fit

  • Timer, animation-frame and subscription ids.
  • The previous value of a prop or state (written in an effect or handler).
  • A flag such as isMounted or "has this request been sent", written in handlers and effects.
  • Any non-visual object you need to keep alive: a WebSocket, an AudioContext, a third-party widget instance.
  • Counters you only need in the console, like a render count while debugging.

Refs versus state

If a value is shown on screen, or if a change must update what the user sees, use state. If it is bookkeeping, use a ref. This demo makes the difference concrete by incrementing both on buttons:

Changing a ref does not update the screen

Click "Add to ref" three times: the console reports ref.current is now 3, but the paragraph still says Ref count shown: 0. Nothing re-rendered, so the JSX that read the ref was never run again. Now click "Add to state": the render finally happens, logs render: state = 1, ref = 3 and the paragraph jumps to 3, because the new render happened to read the ref. That is precisely why you should never display a ref: it shows the value from the last time something else triggered a render.

Don't read or write ref.current during rendering (except for one-time initialization). Rendering must be pure: the same inputs give the same output. A value that can change behind React's back breaks that, so components that do this behave differently with StrictMode, concurrent rendering and the React Compiler. Read and write refs in event handlers and effects. See Keeping Components Pure.

For "set it once, lazily" you can initialize during the first render: if (ref.current === null) { ref.current = createExpensiveThing(); }. That is the single accepted exception.

Job 2: reaching a DOM element

React builds the DOM for you, so you rarely touch it. But some things have no declarative equivalent: focusing an input, scrolling an element into view, playing a <video>, measuring a size, selecting text. For those you need the real DOM node, and you ask for it with a ref.

  1. Create the ref with useRef(null).
  2. Pass it to the JSX element as ref={myRef}.
  3. After React commits the element, it sets myRef.current to the DOM node. When the element is removed, it sets it back to null.
Focus and scroll with DOM refs

"Focus the box" logs focused: true; "Scroll to last" logs scrolled to: Six and the list scrolls so that item is visible. Both handlers use .current after the first render, when the nodes exist.

Rules for DOM refs:

  • current is null before the element mounts and after it unmounts. Inside a handler it is almost always set, but guard against null for conditionally rendered elements.
  • Use refs for non-destructive actions: focus, scroll, measure, play, select. Don't use them to change what React manages (setting textContent, adding or removing child nodes, changing classes that JSX also controls). React would overwrite or lose track of your edits.
  • Don't reach into the DOM for reading values that state already knows. A controlled input already has its value in state (Controlled Inputs and Forms).
  • Prefer the platform for focus where you can: autoFocus on an element, or a <label htmlFor> that moves focus on click.

Refs in lists

You cannot call useRef in a loop, so items.map(() => useRef()) is invalid (Rules of Hooks). Two patterns work:

  1. A single ref holding a Map keyed by item id, filled by callback refs (next section).
  2. Query from a parent ref: attach one ref to the <ul> and use listRef.current.querySelectorAll('li')[index] when needed.

Callback refs and cleanup

Instead of a ref object you may pass a function as ref. React calls it with the DOM node when the element is attached, and (this is the React 19 addition) you can return a cleanup function that React calls when the element is detached. The shape mirrors an effect.

A callback ref with a cleanup function

On load the console logs attached: section "I am a panel". Press "Hide panel" and you get detached: section. Before React 19 the function would have been called with null on detach instead, so you needed an if (node) check. With a returned cleanup, React no longer calls it with null, and the node you attached is the very node you clean up.

An arrow function declared inline in JSX (ref={(node) => ...}) is a new function on every render. React treats a changed ref callback as a different ref: it runs the old cleanup and then the new callback after each render. For work that must happen only when the element appears, define the callback once (outside the component, or with useCallback), as attachPanel could be if it did not need component values.

Callback refs are the way to work with a collection of nodes, or when you must run code at the exact moment a node exists:

JSX
const itemRefs = useRef(new Map());

{items.map((item) => (
  <li
    key={item.id}
    ref={(node) => {
      itemRefs.current.set(item.id, node);
      return () => itemRefs.current.delete(item.id);
    }}
  >
    {item.label}
  </li>
))}

Because a Map is mutated only in ref callbacks (which run during commit, not render), this is allowed.

Passing a ref to your own component

In React 19, ref is an ordinary prop for function components. You receive it in the props object and pass it down to the DOM element. Older code needed forwardRef for this; you can now skip it. (The old wrapper still works, and it is explained in Refs, forwardRef History and useImperativeHandle.)

ref as a prop on a custom component

Press "Sign up" with both boxes empty and the console says name is empty, focusing it; type a name and press again for email is empty, focusing it; fill both and you get thanks, followed by the name. The parent receives real <input> nodes through TextField, which only forwarded the prop.

Handing out a raw DOM node gives the parent full control over it. When a component wants to expose a small, controlled API (focus() and shake() but nothing else) it can use useImperativeHandle, covered in the advanced lessons. For ordinary forms you often don't need refs at all, since controlled inputs or FormData read the values (Uncontrolled Forms, File Inputs and Complex Forms).

The previous value pattern

A ref can hold "the value from last time". Update it in an effect, which runs after render, so that during the next render ref.current still contains the old value.

Remembering the previous value

Click +5 and the console reads render: score 15, previous 10; click -3 and it reads render: score 12, previous 15. This works, but it reads a ref during render, the thing the warning above told you to avoid. It is safe here only because the value is used for logging; if it affected the screen, the output would depend on render timing. The robust alternatives are to store the previous value in state (set when the current value changes) or, better, to avoid needing it: compute the comparison inside the event handler where you know both numbers.

Refs and effects

Refs are also how effects reach values that must not trigger them. Because assigning ref.current never changes any dependency, an effect can read the latest value without listing the ref:

JSX
const latestQuery = useRef(query);
useEffect(() => {
  latestQuery.current = query;
});

useEffect(() => {
  const id = setInterval(() => console.log(latestQuery.current), 1000);
  return () => clearInterval(id);
}, []); // never restarts, always logs the newest query

This pattern is the hand-rolled ancestor of useEffectEvent, which does the same job with a clearer name and lint support (useEffectEvent). Prefer it where available. Also note that refs are not dependencies, because React guarantees the object itself is stable (Effect Dependencies).

Common mistakes

  • Using a ref when state is needed. If the screen must change, use state. A ref that "doesn't update" is behaving correctly.
  • Reading inputRef.current during render. On the first render it is null, and the node does not exist yet. Read refs in handlers and effects.
  • Forgetting null checks for refs on conditional elements.
  • Modifying React-managed DOM (adding children, replacing text) through a ref.
  • Calling useRef in loops or conditions: breaks the order of hooks.
  • Using useRef to store derived data that you could compute each render.
  • Using a ref to silence a StrictMode double effect (hasRun.current). Make the effect idempotent or add proper cleanup (Cleanup, Subscriptions and Timers).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What happens when you assign a new value to myRef.current?

    A ref is a plain mutable box. Assigning to current is just a JavaScript assignment, so nothing is scheduled. Use state when the screen must update.
  2. 2. Which of these is the best use of a ref?

    The interval id is needed later but is never displayed. The other values affect the UI and belong in state.
  3. 3. In React 19, how does a function component receive a ref from its parent?

    React 19 treats ref as an ordinary prop for function components. You destructure it and pass it to a DOM element. forwardRef still works but is no longer required.
  4. 4. What does returning a function from a ref callback do in React 19?

    A function returned from a callback ref acts as its cleanup and runs when the element is removed or the callback changes. React no longer calls the ref with null in that case.
  5. 5. Why is const width = boxRef.current.offsetWidth; written directly in the component body a problem?

    The node does not exist until React commits. Reads belong in handlers or effects, where the DOM is up to date.

Summary

  • useRef(initial) returns a stable { current } object; changing current never causes a render.
  • Use refs for values that are not displayed (timer ids, previous values, instances) and for reaching DOM nodes to focus, scroll, measure or play.
  • Don't read or write ref.current during render, and don't use refs for anything that should appear on screen.
  • Attach DOM refs with the ref attribute: current is null before mount and after unmount.
  • Callback refs can return a cleanup function in React 19, and are the tool for collections of nodes.
  • In React 19, ref is a normal prop on function components, so forwardRef is no longer needed in new code.

Next: useEffectEvent