Thuta Learning
React
IntermediateWeb DevelopmentIntermediate

Refs, DOM Access & Imperative Escape Hatches

ReactLesson 1530 min

What you'll walk away with

  • Explain how a ref differs from state: changing a ref never triggers a re-render
  • Attach ref={myRef} to an element and call DOM methods like focus() from an event handler
  • Store non-visual values such as a timer id in a ref
  • Pass a ref to your own function component as a prop in React 19, without forwardRef

Explain it simply

Refs in plain language

A ref is like a small drawer inside your component. You can put anything in it, it survives every render, and React pays no attention when you swap what is inside: the screen is not redrawn. State is the opposite: every state change makes React render the component again.

You reach for a ref in two situations. The first is to hold a real DOM element that React created, such as an input or a video, so you can do things like move the cursor into a search box when a button is clicked. The second is to remember a value that never appears on screen, such as a timer id, from one render to the next.

Problem → Why → Solution

The problem: a stopwatch that will not stop

You write a small stopwatch with Start and Stop buttons. To clear the interval later, you keep its id in a plain let variable. Start works and the seconds count up, but pressing Stop does nothing: the number keeps climbing, and the console shows no error at all.

BrokenStopwatch.jsx
function Stopwatch() {
  const [seconds, setSeconds] = useState(0);
  let intervalId; // a fresh, empty variable on every render

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

  function stop() {
    clearInterval(intervalId); // this render's copy is still undefined
  }

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

Why Stop does nothing

A component function runs from the top on every render, so let intervalId is a brand-new, undefined variable each time. Start stores the id in the first render's variable, but setSeconds triggers the next render, and the Stop button belongs to that new render, so it clears an empty variable. Putting the id in state would work, but it costs an extra render for a value nobody sees. useRef gives you exactly the missing piece: storage that survives renders and does not cause them.

Core concept: a box that outlives renders

useRef(initialValue) returns a plain object shaped like { current: initialValue }. React creates it on the first render and hands back the very same object on every later render. You can read ref.current and assign to it freely; React does not watch that assignment, so the component does not render again.

The initial value is used on the first render only and ignored afterwards. Each component instance gets its own ref, so two Stopwatches on one page keep two separate timer ids, whereas a module-level variable outside the component would be shared by every instance.

useStateuseRef
Re-render on changeYesNo
How you change itThrough the setterAssign ref.current directly
Read during render?Yes, it drives the UIAvoid; read it in handlers and effects
Typical useData shown on screenDOM nodes, timer ids, previous values

When you write ref={inputRef} on a JSX element, React creates the DOM node and, once it has committed it to the screen, puts the node into inputRef.current. When the element is removed, React sets current back to null. That is why current is still null while the first render is running: use the node in event handlers or effects, which run after the node exists.

Refs are called an escape hatch because they let you step outside React's normal data flow, where a state change leads to a redrawn UI. Focusing, scrolling, selecting text and playing or pausing a video are browser APIs you cannot describe with JSX, so a ref is the natural tool for them. Editing things React itself manages, such as text, classes or child elements, through a ref is different: the DOM drifts away from what React thinks it rendered, so change those through state instead.

A ref is a drawer React does not watch
  1. useRef hands back one stable object
  2. React fills .current after commit
  3. Use .current in handlers or effects
  4. Changing .current never re-renders

If the value must appear on screen, it belongs in state; refs are for values that do not drive the UI.

General pattern

jsx
const someRef = useRef(initialValue);

<element ref={someRef} />   // React sets someRef.current after commit

function handleEvent() {
  someRef.current.someMethod(); // read or write in handlers/effects
}

// React 19: your own function component receives ref as a prop
function Child({ ref, ...props }) {
  return <element ref={ref} {...props} />;
}

Create the ref at the top level of the component, hand it to an element's ref attribute when you need a DOM node, and touch .current only outside rendering, in handlers and effects.

Worked example: focusing a search box from a button

In a task list app it is handy when a 'Focus search' button drops the keyboard cursor straight into the search input. Focus is a browser action you cannot express as state, so the component grabs the DOM node with a ref and calls focus() on it directly.

jsx
import { useRef } from 'react';

export default function SearchBox() {
  const inputRef = useRef(null);
  return <>
    <input ref={inputRef} aria-label="Search tasks" />
    <button onClick={() => inputRef.current?.focus()}>Focus search</button>
  </>;
}

Code breakdown

  1. Create the refconst inputRef = useRef(null);

    It starts as null because no node exists yet. The inputRef object itself is the same on every render.

  2. Attach it to the input<input ref={inputRef} aria-label="Search tasks" />

    As soon as the input is on the screen, React stores its DOM node in inputRef.current. The aria-label gives screen reader users a name for the field.

  3. Use the node in a handler<button onClick={() => inputRef.current?.focus()}>Focus search</button>

    By the time a click happens the node exists, so the browser's focus() method can be called. The ?. guards against the rare case where the input is gone and current is null.

  4. Fragment wrapperreturn <>

    The <> ... </> fragment returns the input and button as siblings without adding an extra wrapper div.

You should see
The button moves keyboard focus to the search input.

Passing a ref to your own component (React 19)

If the input lives inside your own TextField component, how does the parent focus it? Before React 19, function components could not receive ref as a prop, so you wrapped them in forwardRef. In React 19 a function component accepts ref like any other prop and passes it on to an inner element. forwardRef still works, but new code no longer needs it.

SignupForm.jsx
import { useRef } from 'react';

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

export default function SignupForm() {
  const emailRef = useRef(null);
  return (
    <>
      <TextField label="Email" ref={emailRef} />
      <button onClick={() => emailRef.current.focus()}>Fix email</button>
    </>
  );
}

When the parent should get only a few methods such as focus rather than the whole DOM node, useImperativeHandle lets you expose a smaller object. The ref attribute also accepts a function (a ref callback), and in React 19 that function may return a cleanup function, which React calls when the element is removed.

In real projects

Where refs show up in real projects

In production apps most refs are about accessibility and browser APIs. Moving focus to the right place for someone who uses only a keyboard is impossible without one.

  • Form validation: focus the first invalid field after a failed submit so keyboard and screen reader users notice the error at once.
  • Modal dialogs: move focus into the dialog when it opens and return it to the button that opened it when it closes.
  • Chat apps: scroll the newest message into view with scrollIntoView when one arrives.
  • Media and third-party libraries: call video.play(), draw on a canvas, or hand a container DOM node to a chart or map library.
  • Non-DOM values: keep a timer id, a WebSocket instance or the previous value of an input without causing renders.

Common mistakes

Common mistakes with refs

Reading ref.current during render

Writing inputRef.current.value in the component body throws a TypeError on the first render, because current is still null. On later renders it may seem to work while showing a stale value. Touch the node only in handlers or effects.

Expecting the screen to update when a ref changes

If you do clicksRef.current += 1 and wait for <p>{clicksRef.current}</p> to change, it will not: React never learns that the ref changed. The number then jumps suddenly when something else happens to cause a render. Values shown on screen belong in state.

Editing React-managed DOM through a ref

Code like ref.current.textContent = '...' or ref.current.remove() makes the DOM disagree with React's record of it. The next render may silently undo your change or fail with errors about missing nodes. Keep refs for actions React does not manage, such as focusing, scrolling and measuring.

Mini challenge

Mini challenge: a stopwatch that stops

Fix the broken stopwatch from the problem section using a ref. It needs Start, Stop and Reset buttons; pressing Start twice must not create two timers, and the timer must stop if the component is removed.

  • Keep elapsed seconds in state, because they are shown on screen
  • Store the interval id in a useRef, set to null while not running
  • Start must do nothing if a timer is already running
  • Reset stops the timer and returns to 0; an effect cleanup clears the timer on unmount
Stopwatch.jsx
import { useEffect, useRef, useState } from 'react';

export default function Stopwatch() {
  // TODO: elapsed seconds in state, interval id in a ref (start with null)

  function start() {
    // TODO: return early if already running, otherwise start an interval
  }

  function stop() {
    // TODO: clear the interval and mark the ref as not running
  }

  function reset() {
    // TODO: stop, then put the seconds back to 0
  }

  // TODO: useEffect with a cleanup that clears the interval on unmount

  return null; // TODO: show "Elapsed: Ns" and the three buttons
}

Expected: Start makes Elapsed: 1s, 2s ... count up, and pressing Start again does not speed it up. Stop freezes the number, and Start continues from where it stopped. Reset shows Elapsed: 0s and the count stays there.

Show hint

intervalRef.current !== null means a timer is running. Set current back to null after every clearInterval in stop, or Start can never run again. The updater form setElapsed((s) => s + 1) always uses the latest value inside the interval callback.

Show solution
Stopwatch.jsx
import { useEffect, useRef, useState } from 'react';

export default function Stopwatch() {
  const [elapsed, setElapsed] = useState(0);
  const intervalRef = useRef(null);

  function start() {
    if (intervalRef.current !== null) return; // already running
    intervalRef.current = setInterval(() => {
      setElapsed((s) => s + 1);
    }, 1000);
  }

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

  function reset() {
    stop();
    setElapsed(0);
  }

  useEffect(() => {
    return () => clearInterval(intervalRef.current); // stop on unmount
  }, []);

  return (
    <div>
      <p>Elapsed: {elapsed}s</p>
      <button onClick={start}>Start</button>
      <button onClick={stop}>Stop</button>
      <button onClick={reset}>Reset</button>
    </div>
  );
}

Quick quiz 1 / 3

A click handler only does clicksRef.current += 1, and the JSX shows <p>{clicksRef.current}</p>. What do you see after three clicks?

Quick quiz 2 / 3

What is wrong with this component? function NameField() { const ref = useRef(null); console.log(ref.current.value); return <input ref={ref} />; }

Quick quiz 3 / 3

In React 19, a parent wants to focus the input inside your own TextField function component. What is the simplest way?

What to remember

  • useRef returns the same object on every render, and changing ref.current never re-renders
  • With ref={myRef}, React fills current with the DOM node after commit and resets it to null on removal
  • Touch current in handlers and effects; values shown on screen belong in state
  • Use refs for focus, scrolling, media and timer ids, never to edit DOM that React manages
  • In React 19 a function component can take ref as a prop, so forwardRef is no longer needed

Manipulating the DOM with Refs — React

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Refs, DOM Access & Imperative Escape Hatches | Thuta Learning