useMergeRefs

A hook for merging multiple refs into a single stable callback ref.

Made by raouf.codes
Edit on GitHub

Overview

The useMergeRefs hook combines multiple refs into one callback ref. It is useful when a component needs to forward a ref while also keeping an internal ref for measurements, focus handling, or animations.

Logic Lifecycle

  1. Input collection — Accepts a spread of refs (object refs, callback refs, or null)
  2. Callback creation — Returns a single callback ref that assigns to all valid refs
  3. Assignment — When the element mounts/unmounts, updates all refs synchronously

Installation

Usage

Basic

import { useRef } from 'react';
import { useMergeRefs } from '@/hooks/use-merged-refs';

function Input({ ref }: { ref?: React.Ref<HTMLInputElement> }) {
  const internalRef = useRef<HTMLInputElement>(null);
  const mergedRef = useMergeRefs(ref, internalRef);

  return <input ref={mergedRef} />;
}

Merging Callback and Object Refs

const localRef = useRef<HTMLDivElement>(null);

const mergedRef = useMergeRefs(localRef, (node) => {
  if (node) {
    console.log('Node mounted', node);
  }
});

return <div ref={mergedRef} />;

API Reference

useMergeRefs

function useMergeRefs<T>(
  ...refs: (React.Ref<T> | undefined | null)[]
): React.RefCallback<T>;
PropTypeDefault
refs
(React.Ref<T> | undefined | null)[]
-
returns?
React.RefCallback<T>
-

Features

  • Multi-ref support — Merge object refs and callback refs in one place.
  • Stable callback — Returns a memoized callback suitable for React refs.
  • React 19 compatible — Works with current ref patterns and callback cleanup behavior.

Built by raouf.codes. The source code is available on GitHub.

Last updated: 3/21/2026

On this page