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.
npm install react-merge-refsVerified import paths — ran on the pinned version, not inferred.
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.
Ensure your project's React version is compatible with `react-merge-refs@3.x`. Upgrade React to 19 if necessary, or use a `react-merge-refs@2.x` version for older React installations.
Update your import statements from `import mergeRefs from 'react-merge-refs'` to `import { mergeRefs } from 'react-merge-refs'`. For CommonJS environments, ensure your build setup correctly handles ESM or use `const { mergeRefs } = require('react-merge-refs');` for interop if supported.Always ensure `react` and `react-dom` are installed as direct dependencies in your project, even though `react-merge-refs` might list `react` as an optional peer dependency.
Familiarize yourself with React's documentation on refs, especially `React.forwardRef`, `useRef`, and `useImperativeHandle`, to ensure correct application and expected behavior in your components.
Change your import statement to use a named import: `import { mergeRefs } from 'react-merge-refs';`Change your import statement to use a default import: `import mergeRefs from 'react-merge-refs';` or upgrade your `react-merge-refs` package to version 2.0.0 or newer.
If in an ESM project, use `import { mergeRefs } from 'react-merge-refs';`. If in a CJS project, ensure your environment supports ESM interop for `require` or update your build configuration. For older CJS-only environments, consider using `react-merge-refs@^1.x.x` if available and compatible.