React Mastery / React Core Concepts

Forwarding Refs (Old Way)

Before React 19, refs could NOT be passed directly to components.

To forward a ref from a parent to a child, we had to use special APIs.


🧠 Why Ref Forwarding Was Needed

  • Refs do not work on functional components by default

  • Refs attached to class components point to the component instance, not a DOM node

  • To access a child DOM element, ref forwarding was required


❌ Problem

function Input() {
  return <input />;
}

const testRef = React.createRef();
<Input ref={testRef} />; // ❌ ref will NOT work

✅ Solution: React.forwardRef

Syntax

const Component = React.forwardRef((props, ref) => {
  return <element ref={ref} />;
});

🔍 How it works

  1. Parent creates a ref

  2. Parent passes ref to child

  3. forwardRef receives the ref

  4. Ref is attached to <input>

  5. Parent controls the DOM element