Course contentsShow
← React
Lesson 725 of 2,39619. useRefFree lesson

The forwardRef Wrapper Function

Using React.forwardRef to accept a ref argument alongside props in custom components.

The forwardRef Wrapper Function

What you'll learn: How custom components handle ref props in modern React, and how to understand the legacy React.forwardRef wrapper found in older codebases.

Passing Refs in Modern React (React 19+)

Starting in React 19, passing a ref to your custom component is perfectly straightforward: ref is treated as a regular prop. You can destructure it directly from the props object and pass it down to a built-in DOM element.

function MyInput({ ref, placeholder }) {
  // ref is just a normal prop in React 19+
  return <input ref={ref} placeholder={placeholder} />;
}

The Legacy Solution: forwardRef

If you are working on a codebase using React 18 or earlier, you will see a different pattern: React.forwardRef.

Before React 19, the ref prop was treated as a special, internal keyword. It did not arrive in your component's props object; React stripped it away before it reached your component. If a parent tried to pass a ref to a custom component, it was ignored by default.

To solve this, developers had to use the forwardRef wrapper function. It told React: "This component needs to handle refs," and React would then pass the ref as a second argument to the component function, alongside the regular props object.

The Legacy Pattern

import { forwardRef } from 'react';

// forwardRef wraps the component and provides (props, ref)
const MyLegacyInput = forwardRef((props, ref) => {
  return <input ref={ref} {...props} />;
});

Notice the structure of this older pattern:

  1. The component function is wrapped with forwardRef().
  2. The function accepts ref as the second parameter (after props).
  3. That ref is attached to an internal DOM element.

While you no longer need forwardRef when writing new components in React 19 and later, understanding it is crucial for maintaining older React applications and reading existing documentation.

Key Takeaway: In React 19 and later, function components receive ref as a regular prop. React.forwardRef is a legacy API kept for older code, which historically wrapped components to receive the ref as a special second argument.