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.
forwardRef explicitly allows ref propagationuseImperativeHandleThe forwardRef function wraps a component and injects the ref as the second argument after props.
// Defining a component that forwards its ref to an input
const MyInput = React.forwardRef((props, ref) => {
return <input ref={ref} type="text" />;
});
// 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;
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.
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
useImperativeHandle for clean APIsforwardRefuseImperativeHandle