Skip to content
Tutorials Center
My learning

Topics

Lesson 71 of 132 ยท Advanced Patterns

Refs, forwardRef History and useImperativeHandle

Go beyond useRef in React 19 - pass ref as a prop, understand the forwardRef history, expose a small imperative API with useImperativeHandle, use ref callbacks with cleanup, and know when not to.

React is declarative: you describe what the screen should look like for the current state, and React makes the DOM match. Most of the time that is all you need. But a few jobs are inherently imperative: put the cursor in a text box, scroll a list to an item, play a video, measure how wide a paragraph turned out. Those jobs are done by calling a method on a DOM node, and for that you need a ref.

Refs with useRef covers the basics. This lesson is about the advanced end: handing refs from parent to child, the history of forwardRef (and why you can mostly forget it now), designing a small imperative API with useImperativeHandle, ref callbacks with cleanup, measuring, and the discipline of knowing when a ref is the wrong tool.

ref is a prop in React 19

A ref is created with useRef and attached with the ref attribute on a DOM element: <input ref={inputRef} />. After React commits, inputRef.current points at the real <input>.

What if you put ref on your own component? For years, React treated ref as a reserved name like key: it was never passed in props, and function components could not receive it. If you wrote <TextField ref={r} />, React 18 warned that "function components cannot be given refs" and r.current stayed null. You had to wrap the component in forwardRef.

In React 19, ref is simply a prop for function components. You destructure it and pass it on:

ref as an ordinary prop

Click "Check the refs": goodRef.current is INPUT and badRef.current is null. A ref passed to a component does nothing by itself; the component must hand it to an element (or to useImperativeHandle, below). Because the ref arrives in props, you can also pass it through ...rest objects.

The forwardRef history

Before React 19 the same component looked like this:

JSX
import { forwardRef } from 'react';

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

forwardRef wrapped your function, intercepted the special ref and gave it to you as a second argument. It also changed how the component looked in DevTools (a ForwardRef wrapper unless you set a displayName), complicated TypeScript types, and was one more thing every design-system author had to remember on every input and button component.

Facts worth knowing:

  • forwardRef still works in React 19, so existing code keeps running. It is documented as something that will be deprecated in a future version, and codemods exist to remove it. Prefer ref as a prop in new code.
  • Class components never receive ref as a prop; a ref on a class component attaches to the class instance.
  • Libraries that must support React 18 and 19 still use forwardRef. If you publish such a library, keep it until you drop 18.

Exposing less: useImperativeHandle

Passing the raw DOM node up has a cost: the parent can now do anything to it. It can read .value (bypassing your state), set .style, remove children, or call methods you never intended to support. If you later rename the inner element or replace the <input> with a styled widget, every parent that relied on raw DOM access breaks.

useImperativeHandle lets a component decide exactly what the parent's ref contains. Instead of the DOM node, the parent gets a small object with only the methods you choose:

JSX
useImperativeHandle(ref, () => ({ focus, clear }), [deps]);

React calls the function after the commit and assigns the returned object to ref.current. The dependency array works like it does for effects: when a dependency changes, the handle is recreated.

A small imperative API for an input

Type something, press Clear: the text vanishes and focus returns to the field. Press "Inspect handle" and the console prints keys on the handle: focus, clear and value on the handle: undefined. The parent cannot reach .value, .style or any other DOM member, because it never held the DOM node.

Two design notes:

  • Notice that clear uses state (setText('')), not direct DOM mutation. The handle can mix imperative DOM calls (focus) with ordinary React updates. Keep the source of truth in React whenever you can.
  • The array [] is the dependency list. The functions above only use refs and a state setter (both stable), so an empty list is right. If a method reads props or state, list them, or the method would see stale values. Without a dependency array, React recreates the handle on every render.

Keep the surface small

An imperative handle is an API you now maintain. Good handles are tiny and verb-shaped: focus(), scrollToItem(id), play(), reset(). Bad handles mirror all of the component's internals (setValue, getState, setIsOpen...). If you notice the parent calling handle.setIsOpen(true), the open state should have been a prop (isOpen, onOpenChange) instead.

Ref callbacks, cleanup and timing

The ref attribute also accepts a function: a ref callback. React calls it with the DOM node when the element is attached. Callback refs are the right tool when you need to do something at the moment a node appears (observe it, register it in a map, measure it), or when one component has many refs (a ref per list item).

React 19 added a feature that makes callback refs behave like effects: the callback can return a cleanup function, which React runs when the element is removed or when the callback changes. In React 18 and earlier, React instead called your callback with null on detach.

A ref callback with cleanup

On mount you see attach P (count was 0). Press "Add one" and the console shows cleanup P followed by attach P (count was 1). The reason: attach is a new function on every render, and React treats a different ref callback as a reason to detach the old one and attach the new one. Press "Remove the panel": cleanup P runs once more as the node leaves the page.

Practical consequences:

  • Wrap the callback in useCallback if it should only run on mount and unmount. A stable function means no detach/attach on re-render. (Inline arrow functions in ref={...} are fine for cheap work like storing a node, but risky when they set state or create observers.)
  • Return a cleanup instead of checking for null. Old code often wrote if (node) { ... }. In 19, when you return a cleanup, the callback is only ever called with a real node. When you don't return one, React calls your callback with null on detach, exactly as before, so you must still guard.
  • Ref callbacks are the pattern for observers. Create a ResizeObserver or IntersectionObserver for a node when it attaches, and disconnect() it in the cleanup.

Because React 19 treats a returned function as a cleanup, prefer a block body when you only store a node: ref={(node) => { nodes.current = node; }}. The shorthand ref={(node) => (nodes.current = node)} returns the node, which is not a function; the React 19 documentation and TypeScript types steer you away from it. It is harmless in a plain run like ours, but the block body states your intent.

Measuring an element

Reading size and position is a legitimate imperative need. Do it in an effect, a layout effect (when you need the result before paint, see useLayoutEffect and others), a ref callback, or an event handler, never directly during render, because the DOM does not exist yet at that moment on the first render.

Measuring with a ref callback

The text under the box reads Measured: 240 x 70, and the console shows measuring exactly once. The first render cannot know the size, so it prints Not measured yet; the callback measures the box right after commit and stores the result in state, which triggers a second render.

Two details make this safe:

  • The null check. A ref callback that does not return a cleanup function is also called with null when its element detaches (and when React swaps in a different callback). Calling node.getBoundingClientRect() on null throws Cannot read properties of null. Either guard against null or return a cleanup function instead.
  • useCallback keeps the callback stable. An inline function is a new function every render, so React would detach the old one and attach the new one after every render. Here each attach calls setSize with a fresh object, which renders again, which attaches again: a render loop. Running that variant in our editor ends with Error: Maximum update depth exceeded. A stable callback runs once per mount.

For continuous measuring (window resize, content changes) create a ResizeObserver in the callback and disconnect() it in the returned cleanup.

Focus management

The most common reason to touch the DOM in a React app is focus. Moving focus after the UI changes is a correctness and accessibility matter: if a user deletes the item they were on, focus should land somewhere sensible, not vanish to the top of the page. After a failed submit, focus should go to the first invalid field.

The next example puts a focusFirstInvalid method on a form's handle, using a Map of field refs built with ref callbacks. The parent only calls one verb.

Focusing the first invalid field

Press "Sign up" with empty fields: both errors appear. Now press "Jump to first error": the console prints focused: name and the Name input receives focus. Fill in the name but leave the email bad and the same button reports focused: email. The Map is filled by ref callbacks (one per field) and each callback returns a cleanup that deletes its entry, so the map never holds stale nodes.

A tidier real-world variant calls focusFirstInvalid automatically after a failed submit, by running it in the submit handler's follow-up effect, or by using the invalid-handling features the browser already provides. The handle is useful when the parent decides when to focus.

createRef, callback refs and refs in class components

useRef is not the only way to make a ref object. React also exports createRef, the original API from the class-component era, and you will see it in older code. The difference is about identity across renders.

  • useRef(initial) is a hook. It returns the same object on every render of that component instance.
  • createRef() is a plain function. It returns a brand-new { current: null } each time you call it. That is fine in a class, where you call it once in the constructor or in a class field, but inside a function component the ref would be recreated on every render and lose its value. Use useRef there.
JSX
// Class component (legacy style)
class SearchBox extends React.Component {
  inputRef = React.createRef();          // created once per instance

  focus = () => this.inputRef.current?.focus();

  render() {
    return <input ref={this.inputRef} />;
  }
}

A ref attached to a DOM element gives you the DOM node. A ref attached to a class component gives you the component instance, so a parent can call its public methods (child.current.focus()). Function components have no instance, which is why a ref on one was an error before React 19 and is now just an ordinary prop you forward yourself.

createRef in a class, useRef in a function, and a ref to a class instance

The last paragraph shows the main rule of the current property: changing ref.current does not cause a render. The displayed number only catches up when something else (the "Force a render" button) renders the component. Three further rules go with it:

  1. Do not read or write ref.current during rendering. Render must be pure. Read refs in event handlers and effects. The one exception is lazy initialization, such as if (ref.current === null) ref.current = new Thing().
  2. A ref to a DOM node is null until the node is attached, so inputRef.current?.focus() inside an effect or handler needs the node to exist (conditionally rendered elements may be null).
  3. A callback ref is called with the node (React 18 and older: with null when it detaches). It is the right choice when you need to run code the moment the node appears. Before React 19's cleanup return, the idiom was if (node) { ... }.
JSX
// Callback ref in a class (legacy): you store the node yourself
class Measured extends React.Component {
  setBox = (node) => { this.box = node; };
  componentDidMount() { console.log(this.box.offsetWidth); }
  render() { return <div ref={this.setBox}>content</div>; }
}

You may also meet string refs (ref="myInput" and this.refs.myInput). They were removed in React 19; migrate them to createRef or callback refs.

Escape hatches: when not to use a ref

A ref is an escape hatch out of React's declarative model. Every use should have a reason. Before reaching for one, try these:

You want to... Prefer
Show or hide something State and conditional rendering
Change a style or class State plus className / style
Read an input value Controlled input, or FormData on submit
Open and close a dialog An isOpen prop
Tell a child to reset Change its key (see Reconciliation) or lift the state up
Share a value between renders without displaying it useRef (that is a good ref use)

Legitimate imperative uses: focus and text selection, scrolling (scrollIntoView), media playback (play()/pause()), measuring layout, triggering browser APIs that only exist as methods (showModal(), requestFullscreen()), and integrating non-React libraries (maps, charts, editors) that need a DOM node.

Pitfalls to remember:

  • Don't read or write ref.current during render. It is null on the first render and the value can change without React noticing. Use it in handlers and effects.
  • Never mutate DOM that React manages. If you remove a child React rendered, React will later try to remove it again and throw. Changing your own managed text with textContent is the same trap. Changes to an element's children belong to React.
  • A ref may be null. It is null before mount, after unmount, and for conditionally rendered elements. Guard calls when the element might not exist.
  • Handles that change over time need deps. An imperative handle capturing props/state without them will read stale values.
  • Prefer declarative props when a child's behavior is a function of state. <Video playing={isPlaying} /> implemented with an effect that calls play() or pause() is nicer than asking every parent to call videoRef.current.play() at the right moment.

If a component exposes a handle, document its methods and call them only from event handlers or effects. Treat the handle as a small public API, tested like one.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. In React 19, how does a function component receive a ref passed by its parent?

    React 19 treats ref as an ordinary prop on function components. forwardRef is no longer required, although it still works.
  2. 2. A component receives ref as a prop but never attaches it to anything. What is parentRef.current?

    Receiving the prop does nothing by itself. The ref is only filled when it is passed to an element or to useImperativeHandle.
  3. 3. What is the main benefit of useImperativeHandle over passing the DOM node up?

    A custom handle limits what a parent can do (for example focus and clear), so internals can change without breaking callers.
  4. 4. What does a ref callback return in React 19 to run code when the element is removed?

    A function returned from a ref callback is treated like an effect cleanup and runs on detach. Returning the node (an implicit-return arrow) is a mistake.
  5. 5. Which task is better solved with state than with a ref?

    Visibility is part of what the UI looks like, so it belongs in state and conditional rendering. Focus, measuring and media control are genuinely imperative.

Summary

  • In React 19, ref is an ordinary prop on function components: destructure it and attach it to an element. forwardRef still works but is for older code and libraries that support React 18.
  • Receiving a ref does nothing until you attach it to an element or to useImperativeHandle.
  • useImperativeHandle(ref, () => api, deps) exposes a small, intentional API instead of the whole DOM node; keep it to a few verbs and list dependencies.
  • Ref callbacks run when a node attaches and can return a cleanup function; stabilize them with useCallback when they do real work, and prefer block bodies so you never return a value by accident.
  • Measure and focus in handlers, effects or ref callbacks, never in render.
  • Use refs only for genuinely imperative needs: focus, scroll, measure, media and third-party libraries. Everything that changes what the screen shows belongs in state.

Next: Controlled vs Uncontrolled Components