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:- Callback refs: Functions that receive the element as an argument
- RefObject: Objects with a
currentproperty - Cleanup functions: React 19’s ref cleanup return values
- Undefined refs: Gracefully handles
undefinedrefs
- 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
useComposedRefsto 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 usinguseCallback. 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.