Forwarding Refs

Ref forwarding is a technique for automatically passing a ref through a component to one of its children. This is typically not necessary for most components in the application, but it can be useful for some kinds of components, especially in reusable component libraries.

Why Forward Refs?

In standard React components, ref is not a prop (like 'key'). If you pass a ref to a functional component, it won't be passed through to the underlying DOM node or child component. forwardRef allows you to explicitly "forward" that ref.

Basic Syntax

In React 19, functional components can receive ref as a regular prop. However, using forwardRef is still common and explicitly marks a component as ref-forwarding.

JavaScript

import React, { forwardRef } from 'react';

const MyInput = forwardRef((props, ref) => (
  <input ref={ref} className="fancy-input" {...props} />
));

// Usage in parent
function App() {
  const inputRef = React.useRef();

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

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

When to use Ref Forwarding?

Note: Avoid overusing refs. If you can do something declaratively (using state/props), prefer that over using refs.