Capítulo 85 de 116

Chapter 85: forwardRef

Core Idea

forwardRef(render) is the legacy mechanism for letting a function component accept a ref from its parent and forward it to a specific inner DOM node or expose a custom handle — superseded in modern React by accepting ref as a plain component prop directly.

Key Concepts

  • The problem it solved: by default, ref isn't passed through to a function component like other props — a parent trying <MyInput ref={someRef} /> on a plain function component wouldn't reach anything inside it without extra plumbing.
  • Legacy signature: const MyInput = forwardRef((props, ref) => { return <input ref={ref} {...props} />; }) — wraps the component definition, receiving ref as a second argument separate from props.
  • Modern replacement: current React lets a function component simply declare ref as a normal prop (function MyInput({ ref, ...props })) without needing the forwardRef wrapper at all — the docs steer new code toward this simpler, wrapper-free approach.
  • Still combines with useImperativeHandle (Ch 56) the same way either approach does, when the component needs to expose a customized handle rather than the raw DOM node.
  • Existing codebases still use it extensively — understanding forwardRef remains necessary for reading/maintaining code written before the plain-ref-prop capability existed, even though new code shouldn't reach for it.

Code Examples

// Legacy:
const MyInput = forwardRef((props, ref) => <input ref={ref} {...props} />);

// Modern equivalent, no wrapper needed:
function MyInput({ ref, ...props }) {
  return <input ref={ref} {...props} />;
}
  • What it demonstrates: the same "forward a ref to an inner input" behavior, written the legacy wrapped way and the modern plain-prop way.

Key Takeaways

  1. New code should accept ref as a normal destructured prop rather than wrapping the component in forwardRef.
  2. forwardRef remains important to recognize when reading existing/older React codebases.
  3. Whichever form is used, useImperativeHandle is still the tool for customizing exactly what the forwarded ref exposes.

Connects To

  • Ch 56 (useImperativeHandle): customizing what the forwarded ref actually points to.
  • Ch 35 (Manipulating the DOM with Refs): the underlying ref-to-DOM-node mechanism being forwarded here.