Refs and the DOM

Topic 1 of 5 in Refs & effects8 min readIntermediateFree course

Overview

Most of the time React manages the DOM for you and you never touch it directly. But some things can’t be expressed as state and JSX: focusing an input, scrolling to an element, measuring its size, or integrating a non-React library. For these, and for “remembering” values without causing a re-render, React gives you refs.

useRef: a box that survives renders

JSX
import { useRef } from 'react';

function Counter() {
  const ref = useRef(0);

  function handleClick() {
    ref.current = ref.current + 1;
    console.log(`Clicked ${ref.current} times`);
  }

  return <button onClick={handleClick}>Click me</button>;
}

useRef(0) returns an object { current: 0 }. React gives you the same object on every render, and you can read and write ref.current freely. Unlike state, changing it doesn’t trigger a render — the button text above never changes.

useState: changing it re-renders, the value is a snapshot per render, use it for what’s on screen. useRef: changing it does not re-render, it’s mutable and always holds the latest value, use it for timers, DOM nodes and ids. A ref is a box React keeps for you between renders.

When to use a ref instead of state

Refs are for information that your event handlers need but your JSX doesn’t:

  • timer and interval ids,
  • the previous value of something,
  • a DOM node,
  • an AbortController for an in-flight request,
  • whether something has already happened (e.g. “analytics event already sent”).

If the value is shown on screen, it must be state. The stopwatch in this lesson’s exercise uses both: the elapsed time is state (it’s displayed), the interval id is a ref (only the Stop handler needs it).

JSX
const intervalRef = useRef(null);

function handleStart() {
  intervalRef.current = setInterval(tick, 100);
}

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

Don’t touch refs during render

JSX
function Profile() {
  const renderCount = useRef(0);
  renderCount.current++;                       // ✗ writing during render
  return <p>Rendered {renderCount.current}</p>; // ✗ reading during render
}

Rendering must be pure; reading or writing mutable values during render makes output unpredictable (and StrictMode’s double-render will show you why). Use refs only in event handlers and effects. The one exception is lazy initialisation: if (ref.current === null) ref.current = new ExpensiveThing();.

Refs to DOM elements

The most common use of refs is getting hold of a DOM node. Pass the ref object to an element’s ref attribute:

JSX
function SearchBar() {
  const inputRef = useRef(null);

  return (
    <>
      <input ref={inputRef} placeholder="Search courses" />
      <button onClick={() => inputRef.current.focus()}>Focus search</button>
    </>
  );
}

After React creates the <input> and commits it to the DOM, it sets inputRef.current to the DOM node. When the element is removed, React sets it back to null. During the first render inputRef.current is still null — the DOM doesn’t exist yet — which is another reason to only use it in handlers and effects.

Things you can do with DOM refs:

JSX
inputRef.current.focus();
inputRef.current.select();
sectionRef.current.scrollIntoView({ behavior: 'smooth', block: 'start' });
const { width, height } = boxRef.current.getBoundingClientRect();
videoRef.current.play();
dialogRef.current.showModal();

Ref callbacks

Instead of a ref object, you can pass a function. React calls it with the DOM node when the element is attached. In React 19 the function can return a cleanup that runs when the element is removed:

JSX
<li
  ref={(node) => {
    itemsMap.set(course.id, node);
    return () => itemsMap.delete(course.id);
  }}
>
  {course.title}
</li>

Ref callbacks are useful for lists (where you can’t call useRef per item) and for running code the moment a node appears, such as focusing an input that’s just been rendered.

Refs to your own components

What if SearchBar renders your own TextField component, and you want to focus the input inside it?

In React 19, ref is a regular prop for function components. Accept it and pass it to the element that should receive it:

JSX
function TextField({ label, ref, ...props }) {
  return (
    <label>
      {label}
      <input ref={ref} {...props} />
    </label>
  );
}

function SearchBar() {
  const inputRef = useRef(null);
  return (
    <>
      <TextField label="Search" ref={inputRef} />
      <button onClick={() => inputRef.current.focus()}>Focus</button>
    </>
  );
}

In older code you’ll see forwardRef((props, ref) => …). It still works but is no longer needed and will be deprecated.

Exposing a limited API

Sometimes you don’t want parents to have the whole DOM node — just a few methods. useImperativeHandle customises what the ref exposes:

JSX
import { useImperativeHandle, useRef } from 'react';

function VideoPlayer({ src, ref }) {
  const videoRef = useRef(null);

  useImperativeHandle(ref, () => ({
    play: () => videoRef.current.play(),
    pause: () => videoRef.current.pause(),
  }));

  return <video ref={videoRef} src={src} />;
}

// parent: playerRef.current.play()

Use this sparingly. If something can be expressed with props (<Modal isOpen> rather than modalRef.current.open()), props are clearer.

Fragment refs

React 19.3 made Fragment refs stable: a ref on <Fragment> gives you a FragmentInstance that works with all the fragment’s DOM children at once — for example to add an event listener to every child, focus the first focusable element, or observe them all with an IntersectionObserver — without adding a wrapper <div>:

JSX
import { Fragment, useRef } from 'react';

const groupRef = useRef(null);

<Fragment ref={groupRef}>
  <h2>Lessons</h2>
  <LessonList />
</Fragment>

// later, in a handler or effect:
groupRef.current.focus();   // focuses the first focusable element inside

Don’t fight React

Refs are an escape hatch. Reading the DOM is safe; changing DOM that React manages is risky:

JSX
listRef.current.removeChild(firstItem);   // ✗ React still thinks the item exists

React will later try to update or remove that node and crash or show the wrong content. Change the DOM through state and let React do it. It’s safe to modify DOM that React never updates — for example a <div> you leave empty in JSX and hand to a charting or map library.

Rule of thumb: if you’re reaching for a ref to show something, you probably need state. If you need to do something imperative (focus, scroll, play, measure), a ref is the right tool.

Exercise

A stopwatch and an auto-focusing search

Build a Stopwatch with Start, Stop and Reset buttons that shows elapsed seconds with one decimal place. Store the interval id in a ref (it doesn’t affect rendering) and the start/now times in state. Then build SearchDialog with a button that opens a search input and focuses it, and a SearchInput component that accepts a ref prop and passes it to its <input>.

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

export function Stopwatch() {
  // your code here
}

export function SearchInput(/* props */) {
  // your code here
}

export function SearchDialog() {
  // your code here
}

Summary

  • useRef(initial) returns a stable { current } object that survives renders; changing it doesn’t re-render.
  • Use refs for values that don’t affect what’s on screen: timer ids, previous values, DOM nodes.
  • Pass a ref to a JSX element’s ref attribute to get its DOM node after React commits.
  • In React 19, ref is a normal prop for function components — no forwardRef needed.
  • Don’t read or write ref.current during render; use refs in event handlers and effects.