Goodbye forwardRef: Refs as Props in React 19
Passing a ref to a custom component used to require wrapping it in forwardRef. In React 19, function components simply receive ref as a prop.
Before and after
// React 18
const Input = forwardRef(function Input(props, ref) {
return <input ref={ref} className="input" {...props} />;
});
// React 19
function Input({ ref, ...props }) {
return <input ref={ref} className="input" {...props} />;
}
Using it is unchanged:
function SearchBox() {
const inputRef = useRef(null);
return (
<>
<Input ref={inputRef} placeholder="Search..." />
<button onClick={() => inputRef.current.focus()}>Focus</button>
</>
);
}
Ref callbacks can clean up
A callback ref can now return a cleanup function, like an effect. This is handy for observers and third-party widgets.
<div
ref={(node) => {
const observer = new ResizeObserver(([entry]) => setWidth(entry.contentRect.width));
observer.observe(node);
return () => observer.disconnect(); // runs when the element is removed
}}
/>
Exposing a custom API
function VideoPlayer({ ref, src }) {
const videoRef = useRef(null);
useImperativeHandle(ref, () => ({
play: () => videoRef.current.play(),
pause: () => videoRef.current.pause(),
}));
return <video ref={videoRef} src={src} />;
}
Migrating
forwardRefstill works, but React plans to deprecate it in a future version, so migrate gradually.- With TypeScript, type the prop as
ref?: React.Ref<HTMLInputElement>or useReact.ComponentProps<'input'>, which includesref. - Class components still don't receive
refas a prop.
Was this article helpful?
Comments
No comments yet. Have a question or a tip? Be the first to share it.