Skip to main content
composeRefs provides utilities to compose multiple React refs together, allowing you to forward refs to multiple destinations. This is essential when building reusable components that need to manage both internal refs and forward refs from parent components.

Installation

Functions

composeRefs

Composes multiple refs into a single ref callback function.

useComposedRefs

A React hook that composes multiple refs with proper memoization.

Type Definitions

Usage

Basic Composition with useComposedRefs

Multiple Internal Refs

With Callback Refs

Direct composeRefs Usage

With React 19 Ref Cleanup

Building a Reusable Button

Implementation Details

The utilities handle:
  1. Callback refs: Functions that receive the element as an argument
  2. RefObject: Objects with a current property
  3. Cleanup functions: React 19’s ref cleanup return values
  4. Undefined refs: Gracefully handles undefined refs
Key features:
  • Automatically detects and calls cleanup functions (React 19+)
  • Safely handles null/undefined refs
  • Works with both mutable ref objects and callback refs
  • Properly memoized in useComposedRefs to avoid unnecessary re-renders

Differences Between composeRefs and useComposedRefs

  • composeRefs: Returns a new ref callback every time. Use when you don’t need memoization.
  • useComposedRefs: Returns a memoized ref callback using useCallback. Use in components to avoid unnecessary re-renders.

Notes

useComposedRefs automatically memoizes the composed ref based on the input refs, preventing unnecessary re-renders when passed as props.
The utilities support React 19’s ref cleanup feature. When a callback ref returns a function, that function will be called when the ref is detached or replaced.
Both utilities handle the differences between callback refs and RefObject refs transparently, so you can mix and match different ref types.