Skip to content
Tutorials Center
My learning

Topics

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.

JSX
import { forwardRef } from 'react';

const FancyInput = forwardRef(function FancyInput(props, ref) {
  return <input ref={ref} {...props} />;
});

Try it

Focus a child's input from the parent
Expose a small API with useImperativeHandle

Syntax

TypeScript
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 ref argument can be null. 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 useImperativeHandle to expose a narrow set of methods such as focus().
  • Set displayName or pass a named function to forwardRef(function Name() {}), otherwise DevTools show ForwardRef.
  • Combining memo and forwardRef: 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 reads ref from its props. A codemod from the React team automates this. forwardRef will be deprecated in a future release.
  • Class components do not use forwardRef for themselves: a ref on a class component gives the instance.