React Reference ยท Top-Level React APIs
React ref as a prop (React 19)
Reference for receiving refs as an ordinary prop in React 19 function components, ref callback cleanup functions, class component limits and migration.
Starting with React 19, function components receive ref in their props like any other prop. A parent writes <MyInput ref={inputRef} />, and MyInput reads ref from its props and attaches it to an element. The forwardRef wrapper that older code needed is no longer necessary.
Everything else about refs stays the same: a ref object created with useRef gets .current set to the DOM node after the commit, and a callback ref is called with the node.
function MyInput({ ref, ...rest }) { return <input ref={ref} {...rest} />; }
Try it
The first console line shows attached DIV. After you press Toggle, cleanup for DIV appears: the function returned by a callback ref runs when the node is removed (or the callback changes).
Syntax
function Component({ ref, ...otherProps }) { return <element ref={ref} />; } <Component ref={refObjectOrCallback} />
| Form | Description |
|---|---|
| Ref object | The result of useRef(null) (or createRef() in classes). React sets .current to the node, and back to null on unmount. |
| Callback ref | A function called with the node on mount. In React 19 it may return a cleanup function, which runs on unmount instead of a call with null. |
Usage notes
- Cleanup return value changes callback refs. When a callback ref returns a function, React calls that function on unmount and no longer calls the ref with
null. An arrow function with an implicit return such asref={(node) => (el = node)}now returns the assigned value, which the React 19 TypeScript types reject. Write it with braces:ref={(node) => { el = node; }}. - It is only for function components. A ref on a class component still gives the class instance; the instance does not get a
refprop. - Reading
element.refon a React element is deprecated. In React 19 useelement.props.ref. - Hide implementation details when needed. Passing
refstraight through exposes the DOM node. To expose only some methods, combine it withuseImperativeHandle(ref, ...). - Spread carefully.
{...props}now includesref, which is handy for wrappers but can overwrite a ref you set earlier. Put your ownrefafter the spread if you need to merge or override. - Version note: React 18 and earlier do not pass
refin props. Libraries that support both keep usingforwardRef. - TypeScript: declare
ref?: React.Ref<HTMLInputElement>in the props type, or useReact.ComponentProps<'input'>, which includes it.
Related
- forwardRef, createRef, cloneElement
- Lessons: useRef, Refs and imperative handles