React Ref Merging Utility

3.0.2 · active · verified Sun Apr 19

react-merge-refs is a concise utility designed for React developers to combine multiple ref objects or functions into a single ref callback. This is particularly useful in component development where a local ref (e.g., from `useRef`) needs to be managed alongside an external ref passed via `React.forwardRef`. The library currently stands at version 3.0.2, actively maintained with releases addressing bug fixes and support for new React versions, including React 19. It aims to simplify the complexities of React's ref system, abstracting away the differences between various ref types (object refs, function refs) and ensuring compatibility across React versions, thereby preventing common pitfalls when trying to assign multiple refs to a single DOM element or component.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to use `mergeRefs` with `React.forwardRef` and `React.useRef` to combine both a local component ref and an externally forwarded ref onto a single DOM element.

import React from 'react';
import { mergeRefs } from 'react-merge-refs';

interface ExampleProps {
  // Other props
}

const Example = React.forwardRef<HTMLDivElement, ExampleProps>(function Example(props, ref) {
  const localRef = React.useRef<HTMLDivElement>(null);

  // When merging refs, ensure all refs are handled.
  // It's common to have a local ref and a forwarded ref.
  return (
    <div
      ref={mergeRefs([localRef, ref])}
      style={{ border: '1px solid blue', padding: '10px' }}
    >
      This is an example component.
      <button onClick={() => {
        if (localRef.current) {
          localRef.current.style.backgroundColor = 'yellow';
          console.log('Local ref current:', localRef.current);
        }
      }}>Highlight Local Ref</button>
    </div>
  );
});

// Usage in another component:
const App = () => {
  const appRef = React.useRef<HTMLDivElement>(null);

  React.useEffect(() => {
    if (appRef.current) {
      console.log('App ref current:', appRef.current);
      appRef.current.style.border = '2px dashed red';
    }
  }, []);

  return <Example ref={appRef} />;
};

export default App;

view raw JSON →