React / 83
ref as a prop, ref callbacks & useImperativeHandle
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
export default function SearchBox({ label, ref }) {
return (
<label>
{label}
<input ref={ref} type="search" />
</label>
);
}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} />SearchBox.jsx (child)
function SearchBox({ ref })
<input ref={ref} />searchRef.current
The real <input> 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
}}
/>- attachThe element is added. React calls
ref(node): start observing, store it in a Map… - re-renderIf you passed a different function, React calls the old cleanup, then the new callback with the same node.
- detachThe element is removed. React calls the cleanup you returned: stop observing, delete it from the Map.
- dev onlyStrictMode runs one extra attach, cleanup, attach on mount to check your cleanup really undoes the setup.
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:
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:
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" />
- Call a method on the handle.
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.
