Skip to content

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.

tsx

Usage guidelines

  • Use it when a component needs the element and the caller passes a ref: the internal ref and the caller's ref both receive the same element.
  • Pass object refs, callback refs or nothing: null and undefined entries are skipped. When every entry is empty, the hook returns null.
  • 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 render element or useRender: Base UI parts and useRender already merge their ref with the render element's ref.
  • Skip it when one ref is enough: forward the caller's ref directly 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.

tsx

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.

Shared parameters
ParameterTypeDescription
a requiredInputRef<I>No description
b requiredInputRef<I>No description

Returns

Result<I>