← Back to Chapters

Forwarding Refs in React

? Forwarding Refs in React

? Quick Overview

Forwarding Refs is an advanced React pattern that allows a parent component to directly access a DOM element inside a child component. Normally, refs stop at component boundaries, but ref forwarding intentionally passes them through.

This pattern is implemented using the React.forwardRef API and is especially useful for reusable UI components such as inputs, buttons, and form controls.

? Key Concepts

  • Refs are used for imperative actions like focusing or scrolling
  • By default, refs do not pass through components
  • forwardRef explicitly allows ref propagation
  • Only works with functional components
  • Commonly paired with useImperativeHandle

? Syntax / Theory

The forwardRef function wraps a component and injects the ref as the second argument after props.

? View Code Example
// Defining a component that forwards its ref to an input
const MyInput = React.forwardRef((props, ref) => {
return <input ref={ref} type="text" />;
});

? Code Example

? View Code Example
// Parent component controlling child input using forwarded ref
import React, { useRef } from "react";

const InputBox = React.forwardRef((props, ref) => {
return <input ref={ref} placeholder="Type here..." />;
});

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

const focusInput = () => {
inputRef.current.focus();
};

return (
<div>
<InputBox ref={inputRef} />
<button onClick={focusInput}>Focus Input</button>
</div>
);
}

export default App;

? Live Output / Explanation

When the button is clicked, the cursor moves directly into the input field. Although the input exists inside a child component, the parent can still control it because the ref is forwarded to the actual DOM node.

? Interactive Flow

1️⃣ Parent creates a ref using useRef
2️⃣ Parent passes the ref to a child component
3️⃣ Child forwards the ref to a DOM element
4️⃣ Parent performs imperative actions like focus or scroll

? Common Use Cases

  • Building reusable input and form components
  • Programmatically focusing elements
  • Creating design system components
  • Integrating third-party DOM libraries

? Tips & Best Practices

  • Use ref forwarding sparingly
  • Prefer props for declarative data flow
  • Document forwarded refs clearly
  • Combine with useImperativeHandle for clean APIs

? Try It Yourself

  • Create a reusable Button component using forwardRef
  • Auto-focus an input on page load
  • Expose custom methods using useImperativeHandle