useMergedRef
Combines any number of callback and object refs into one, with React 19 ref cleanup for each of them.
pnpm dlx shadcn@latest add https://hextaui.com/r/use-merged-ref.jsonAdds the hook and anything it depends on to your project.
Copy and paste the following code into your project.
hooks/use-merged-ref.ts Update the import paths to match your project setup.
An element has one ref, but components often need to hand it to several places: the parent that forwarded a ref, a local ref for effects, and hooks that work through a callback ref.useMergedRef returns one callback that feeds all of them.
When the element attaches, every ref receives it. Object refs get .current set, and callback refs are called with the node. The merged callback returns a cleanup in the React 19 style. On detach it runs each callback ref's own cleanup, or calls the ref with null if it didn't return one, and resets object refs to null.
That makes callback refs a good home for anything tied to the element's lifetime, like observers and listeners. Setup and teardown live together, and merging them with other refs keeps them working.
- The merged callback changes whenever any ref changes. An inline arrow is a new ref on every render, so React detaches and reattaches the element each time. Wrap callback refs in
useCallback. undefinedandnullrefs are skipped, so you can pass optional props straight in.- For one forwarded ref plus a local object ref, useComposedRef is shorter.
| Prop | Type | Default |
|---|---|---|
...refsObject refs, callback refs or undefined. | Array<Ref<T> | undefined> | – |
| Returns | Description |
|---|---|
(node: T | null) => () => void | Pass to the element's ref. Returns the combined cleanup. |
Field and InputGroup.