React Reference ยท Top-Level React APIs
React forwardRef() function
Reference for React forwardRef: let a component expose a DOM node to its parent through a ref, with useImperativeHandle, and why React 19 makes it optional.
forwardRef lets a component receive the ref that its parent attached and pass it on to one of its own elements. Without it (before React 19), <MyInput ref={ref} /> would not work on a function component: the ref attribute was not part of the props, and React warned that function components cannot be given refs.
In React 19, ref is a normal prop for function components, so forwardRef is no longer needed in new code. It still works, so existing code keeps running, and you need it when you support React 18. See ref as a prop.
import { forwardRef } from 'react'; const FancyInput = forwardRef(function FancyInput(props, ref) { return <input ref={ref} {...props} />; });
Try it
Syntax
function forwardRef<T, P = {}>( render: (props: P, ref: ForwardedRef<T>) => ReactNode ): ForwardRefExoticComponent<P & RefAttributes<T>>;
| Name | Description |
|---|---|
render |
A render function that takes props and ref as two arguments and returns JSX. React calls it as your component. |
props |
The props passed by the parent, without ref. |
ref |
The ref from the parent: a ref object, a callback ref, or null if the parent did not pass one. |
Returns: a component you can render. It accepts the original props plus ref.
Usage notes
- The
refargument can benull. Passing it on to an element is safe:<input ref={null} />does nothing. - Do not expose more than needed. Forwarding a raw DOM node lets the parent do anything with it. Use
useImperativeHandleto expose a narrow set of methods such asfocus(). - Set
displayNameor pass a named function toforwardRef(function Name() {}), otherwise DevTools showForwardRef. - Combining
memoandforwardRef: wrap in this order:memo(forwardRef(...)). - Only the DOM node or handle: a ref passed this way points at what the child chose to attach it to; the parent cannot see the child's state.
- Migrating to React 19: replace
forwardRef((props, ref) => ...)with a plain function that readsreffrom its props. A codemod from the React team automates this.forwardRefwill be deprecated in a future release. - Class components do not use
forwardReffor themselves: a ref on a class component gives the instance.
Related
- ref as a prop, createRef, memo
- Lessons: Refs and imperative handles, useRef