Skip to main content

forwardRef

Pass ref down to a child component. This is mainly used in libraries with higher-order components that wrap other components. Using forwardRef, there is an easy way to get a reference to the wrapped component instead of the wrapper itself.

Signature

ForwardRefRenderFunction<T, P>
required
A render function that receives props and a forwarded ref.
FunctionalComponent
A functional component that forwards refs to the inner component.

Usage

Basic Example

Forward a ref to a DOM element:

With TypeScript

Type the ref and props correctly:

Higher-Order Component

Forward refs through a HOC:

Imperative Handle

Expose custom methods through the ref:

Implementation Details

The forwardRef implementation in Preact:

Key Features

  1. Ref Removal: The ref prop is removed from the props object passed to the render function
  2. Symbol Marking: Sets $$typeof to Symbol.for('react.forward_ref') for React compatibility
  3. Display Name: Automatically generates a display name for debugging
  4. MobX Compatibility: Includes special handling for mobx-react compatibility

ForwardedRef Type

The ref parameter can be:

Best Practices

  1. Type Safety: Always type your refs in TypeScript for better IDE support
  2. Display Names: Set a displayName on your render function for better debugging
  3. Null Checks: Always check if the ref exists before using it
  4. Documentation: Document what the ref exposes when using useImperativeHandle

Common Patterns

Conditional Ref Forwarding

Multiple Refs

Source

Implementation: compat/src/forwardRef.js:1-32