Skip to content
ClapelloNotes by Barath
ReactCh 15 · 2/6
Core5 min readUpdated

React / 83

ref as a prop, ref callbacks & useImperativeHandle

TL;DR

In React 19 a component takes ref like any other prop, so forwardRef isn't needed. Ref callbacks can return a cleanup, and useImperativeHandle exposes a small API.

ref is a prop now

SearchBox.jsx
export default function SearchBox({ label, ref }) {
  return (
    <label>
      {label}
      <input ref={ref} type="search" />
    </label>
  );
}
App.jsx
import { useRef } from "react";
import SearchBox from "./SearchBox";
 
export default function App() {
  const searchRef = useRef(null);
 
  return (
    <>
      <SearchBox label="Find a dish" ref={searchRef} />
      <button onClick={() => searchRef.current.focus()}>Focus search</button>
    </>
  );
}

App.jsx (parent)

const searchRef = useRef(null)

<SearchBox ref={searchRef} />
ref is just a prop

SearchBox.jsx (child)

function SearchBox({ ref })

<input ref={ref} />
React fills it in on commit

searchRef.current

The real <input> DOM node

the parent can now call searchRef.current.focus()
The parent owns the ref. SearchBox takes it like any other prop and puts it on the input, so the parent ends up holding the real DOM node.

Nothing new to learn: you read ref from props and pass it on, exactly like label.

What older code looks like

Before React 19, ref was taken out of props, so you needed a wrapper called forwardRef. You'll meet it in older projects and in libraries that still support React 18.

function SearchBox({ label, ref }) {
  return <input ref={ref} aria-label={label} />;
}
import { forwardRef } from "react";
 
const SearchBox = forwardRef(function SearchBox({ label }, ref) {
  return <input ref={ref} aria-label={label} />;
});

Ref callbacks: a function instead of an object

ref also accepts a function. React calls it with the DOM node when the element is added. In React 19 it can return a cleanup, which React calls when the element is removed.

<img
  src={dish.photo}
  alt={dish.name}
  ref={(node) => {
    observer.observe(node);                 // element added
    return () => observer.unobserve(node);  // element removed
  }}
/>
  1. attachThe element is added. React calls ref(node): start observing, store it in a Map…
  2. re-renderIf you passed a different function, React calls the old cleanup, then the new callback with the same node.
  3. detachThe element is removed. React calls the cleanup you returned: stop observing, delete it from the Map.
  4. dev onlyStrictMode runs one extra attach, cleanup, attach on mount to check your cleanup really undoes the setup.
React 19: return a cleanup from the ref callback. An inline callback is a new function every render, so React runs the old cleanup and calls the new one each time.

The classic use is a ref for every item in a list. You can't call useRef in a loop (that breaks the rules of hooks), so keep one Map in a ref and fill it from callbacks:

Menu.jsx
import { useRef } from "react";
 
export default function Menu({ dishes }) {
  const itemsRef = useRef(new Map());
 
  function scrollTo(id) {
    itemsRef.current.get(id).scrollIntoView({ behavior: "smooth", block: "nearest" });
  }
 
  return (
    <ul>
      {dishes.map((dish) => (
        <li
          key={dish.id}
          ref={(node) => {
            itemsRef.current.set(dish.id, node);
            return () => itemsRef.current.delete(dish.id);
          }}
        >
          {dish.name}
        </li>
      ))}
    </ul>
  );
}

scrollTo runs from a click, after the commit, so every node is in the Map by then.

useImperativeHandle: hand over a remote, not the TV

Passing the ref straight to the <input> gives the parent the whole DOM node: it could change styles, remove children, anything. If you only want it to call a couple of methods, build a small object with useImperativeHandle:

SearchBox.jsx
import { useImperativeHandle, useRef } from "react";
 
export default function SearchBox({ ref }) {
  const inputRef = useRef(null);
 
  useImperativeHandle(ref, () => ({
    focus() {
      inputRef.current.focus();
    },
    clear() {
      inputRef.current.value = "";
    },
  }), []);
 
  return <input ref={inputRef} type="search" />;
}

Now searchRef.current in the parent is { focus, clear }, not the input. The signature is useImperativeHandle(ref, createHandle, dependencies?). Like useMemo, the handle is rebuilt only when a dependency changes.

A handle, not the whole input

Try it

<SearchBox ref={searchRef} label="Find a dish" />

  1. Call a method on the handle.
The parent holds searchRef. SearchBox only exposes focus() and clear(), so anything else on the handle is undefined.

Don't

Imperative API for things props can do

modalRef.current.open();
modalRef.current.close();

The parent now has to remember to call these at the right time, and the open state is hidden inside the modal.

Do

Describe it with a prop

<Modal isOpen={isOpen} onClose={() => setIsOpen(false)} />

Keep refs for things props can't say: focus, scroll, select text, play media.

Gotchas

Recall

Can you answer these?

0/4

Answer out loud (or in your head) before you tap. That's what makes it stick.

Saved on this device only. No login.