useMergedRefs
Combines several refs into one memoized callback ref.
useMergedRefs combines up to four refs into a single callback ref, so a component can keep its own ref to an element while forwarding the caller's ref to the same element. It is useMergedRefs from @base-ui/utils, re-exported through a Dify UI subpath.
Usage guidelines
- Use it when a component needs the element and the caller passes a ref: the internal ref and the caller's
refboth receive the same element. - Pass object refs, callback refs or nothing:
nullandundefinedentries are skipped. When every entry is empty, the hook returnsnull. - Rely on callback-ref cleanup: a callback ref that returns a cleanup function has it called when the element detaches or the merged refs change.
- Do not merge refs for a
renderelement oruseRender: Base UI parts anduseRenderalready merge theirrefwith therenderelement's ref. - Skip it when one ref is enough: forward the caller's
refdirectly when the component does not read the element itself.
Each input ref may be a React ref, null or undefined. The result is a callback ref or null.
The returned callback stays the same while the refs passed in are the same, so the element is not detached and reattached on every render.
Examples
Focus a forwarded input from a shortcut
The component needs the element for the / shortcut, and the caller's ref still receives the same input.
API reference
useMergedRefs
Merges refs into a single memoized callback ref or null. This makes sure multiple refs are updated together and have the same value.
This function accepts up to four refs.
| Parameter | Type | Description |
|---|---|---|
a required | InputRef<I> | No description |
b required | InputRef<I> | No description |
Returns
Result<I>