Skip to article content
FrontendXLesson 06 / 40

Refs, the DOM and Imperative Escape Hatches

Build, explain and debug React 19 interfaces: components, rendering, state, effects, identity, forms and actions, server components, concurrency, performance and testing, ending with architecture and typing work on real component challenges.

intermediate · about 50 minutes · 4 exercises

  • Predict
  • Implement
  • Debug
  • Test

What you will be able to do

#
  • Read and write DOM nodes with useRef.
  • Pass refs as ordinary props in React 19 without forwardRef.
  • Return cleanup functions from ref callbacks.

Overview

#

Refs hold values across renders

useRef returns a mutable object with a .current field. Changing .current does not trigger a re-render. Use refs to store values that are not part of the rendered output, such as a timer id or a previous value.

snippet.tsx
const inputRef = useRef<HTMLInputElement>(null);

function focus() {
  inputRef.current?.focus();
}

return <input ref={inputRef} />;

Ref as a prop in React 19

In React 19, ref is a normal prop for function components. You no longer need forwardRef to accept a ref and attach it to a DOM node.

snippet.tsx
function TextInput({ ref, ...props }: React.ComponentPropsWithRef<"input">) {
  return <input ref={ref} {...props} />;
}

forwardRef still works for compatibility, but new code can pass ref directly. This also means ref can be destructured like any other prop.

Ref callbacks and cleanup

A ref can be a callback instead of an object. React calls it with the node on attach and with null on detach. React 19 also lets a ref callback return a cleanup function, which React runs on detach. This removes the need for the null check.

snippet.tsx
function Measure() {
  const [width, setWidth] = useState(0);
  return (
    <div
      ref={(node) => {
        if (!node) return;
        const observer = new ResizeObserver(() => setWidth(node.clientWidth));
        observer.observe(node);
        return () => observer.disconnect();
      }}
    >
      {width}px
    </div>
  );
}

When to reach for a ref

Use refs for focus management, text selection, media playback, measuring layout, and integrating non-React libraries. Do not use refs to store values that should drive rendering; that is what state is for. A ref read during render is a sign the value should be state.

useImperativeHandle

When a parent needs a limited imperative API from a child, useImperativeHandle exposes only the methods you choose instead of the whole DOM node.

Exercises

#

Reference answers and expected output are authored, not executed in this browser. Nothing you type is run, and there is no Run or Pass control on this page.

  1. Exercise 1Predict

    How many times does this component render when the button is clicked?

    Read the code, then choose the best answer. The reference explanation stays hidden until you respond.
    stimulus.tsx
    function Box() {
      const count = useRef(0);
      console.log("render");
      return (
        <button onClick={() => { count.current += 1; }}>
          {count.current}
        </button>
      );
    }
    Choose the best answer
  2. Exercise 2Implement

    Implement a SearchBox that focuses its input when the component mounts, using a ref.

    starter.tsx
    export function SearchBox() {
      return <input />;
    }

    Reveal the reference answer
    reference.tsx
    import { useEffect, useRef } from "react";
    
    export function SearchBox() {
      const ref = useRef<HTMLInputElement>(null);
      useEffect(() => {
        ref.current?.focus();
      }, []);
      return <input ref={ref} aria-label="Search" />;
    }

    Authored expected output: The input receives focus after mount.

    Focus is an imperative DOM action, so it belongs in an effect after commit, when the node exists. The optional chaining guards against a null ref.

  3. Exercise 3Debug

    This ref callback leaks a ResizeObserver. Fix it using the React 19 cleanup return.

    starter.tsx
    ref={(node) => {
      if (node) {
        const obs = new ResizeObserver(onResize);
        obs.observe(node);
      }
    }}

    Reveal the reference answer
    reference.tsx
    ref={(node) => {
      if (!node) return;
      const obs = new ResizeObserver(onResize);
      obs.observe(node);
      return () => obs.disconnect();
    }}

    Authored expected output: The observer is disconnected when the node detaches.

    React 19 allows a ref callback to return a cleanup function that React calls on detach. Returning the disconnect removes the need to handle the null case manually and prevents the observer from leaking.

  4. Exercise 4Test

    Describe a test that proves SearchBox focuses its input on mount.

    starter.tsx
    render(<SearchBox />)

    Reveal the reference answer
    reference.tsx
    Render SearchBox, then assert that the element with the accessible name Search has document.activeElement equal to it, or use toHaveFocus from the DOM matchers.

    Authored expected output: One assertion: the search input has focus after render.

    Focus is observable through document.activeElement. Query by accessible name so the test also checks the aria-label wiring.

Common misconceptions

#
  • Changing ref.current re-renders the component. It does not; refs are outside the render output.
  • You must use forwardRef to pass a ref in React 19. ref is a normal prop for function components.
  • Ref callbacks must handle the null case. In React 19 they may return a cleanup function instead.
  • Refs are for storing render data. Refs are for values that do not affect output; render data belongs in state.

Follow-up practice

#
  • react-performance-and-identity
  • react-debugging-and-error-handling

Related resources

#

Your progress

#

Answers, drafts and completion marks are stored only in this browser. Nothing is sent to a server and no account is used.

Verification: authored. Answers and outputs on this page are authored reference material, not executed results.

© 2026 FrontendX. All rights reserved.