What is Forwarding Refs in React?

Ref forwarding is a technique in React that allows a component to take a ref it receives from a parent and pass (or “forward”) it further down to one of its child components. This article provides a clear overview of why ref forwarding is necessary, how to implement it using the React.forwardRef API, and the most common scenarios where this pattern is highly beneficial.

The Problem with Standard Refs and Custom Components

In React, references (refs) provide a way to access the underlying DOM nodes or React element instances directly. Normally, you might use a ref to manage focus, select text, or trigger animations.

However, you cannot pass a ref attribute to a custom function component the same way you pass standard props. Because function components do not have instances, React treats the ref attribute specially—similar to the key prop—and does not pass it down to the component’s argument list. If you attempt to access props.ref, it will return undefined.

How Ref Forwarding Works

To solve this issue, React provides the React.forwardRef API. This function wraps a component, intercepting the ref passed to it, and exposes it as a second argument to the component’s render function.

Here is how you define a component with ref forwarding:

import React, { forwardRef } from 'react';

const CustomInput = forwardRef((props, ref) => {
  return <input ref={ref} {...props} type="text" />;
});

export default CustomInput;

In this example, CustomInput is a React component that forwards its ref directly to the native HTML <input> element inside it.

Consuming a Forwarded Ref

Once you have created a component that forwards refs, parent components can interact with the inner DOM node as if they were targeting it directly:

import React, { useRef } from 'react';
import CustomInput from './CustomInput';

function ParentComponent() {
  const inputRef = useRef(null);

  const focusInput = () => {
    // Directly focus the input element inside CustomInput
    inputRef.current.focus();
  };

  return (
    <div>
      <CustomInput ref={inputRef} placeholder="Type here..." />
      <button onClick={focusInput}>Focus Input</button>
    </div>
  );
}

When the ParentComponent mounts, inputRef.current points to the native <input> DOM node inside CustomInput.

When to Use Ref Forwarding

Ref forwarding is highly useful in specific scenarios: