What is ref forwarding in React?
In a nutshell
Ref forwarding is the technique of creating a component that receives a ref, and passing (“fowarding”) that ref down to a child (usually DOM node).
Here’s an example of ref forwarding:
const FancyButton = React.forwardRef((props, ref) => (
<button ref={ref} className="FancyButton">
{props.children}
</button>
));
// You can now get a ref directly to the DOM button:
const ref = React.createRef();
<FancyButton ref={ref}>Click me!</FancyButton>;
FancyButton
uses React.forwardRef
to obtain a ref passed to it, and passes down that ref to a child button
DOM element.
Now, components that use FancyButton
can use a ref to access the underlying button
element. The ref is said to be “forwarded” from the component that uses FancyButton
down to the button
DOM element.
When to use ref forwarding?
In most cases, React components should hide their implementation details so that other components that use them don’t rely heavily on their DOM structure.
But if you’re creating base components that are used as a replacement for native DOM elements (e.g., button
, select
, input
), it’s often convenient to be able to access underlying DOM nodes in order to manage focus, selection, or animation.