Skip to main content

Function: useMergedRefs()

@arolariu/components


@arolariu/components / useMergedRefs

Function: useMergedRefs()

useMergedRefs<T>(...refs): (instance) => void | (() => VoidOrUndefinedOnly)

Defined in: hooks/useMergedRefs.tsx:29

Merges multiple refs into a single callback ref.

Type Parameters

T

T

The type of the element being referenced.

Parameters

refs

...Ref<T>[]

An array of refs to merge. Can include callback refs, ref objects, or undefined.

Returns

A callback ref that updates all provided refs.

(instance) => void | (() => VoidOrUndefinedOnly)

Remarks

This hook is essential when you need to attach multiple refs to the same element, such as combining a forwarded ref with an internal ref for measurements or imperative operations. All provided refs will receive the same element instance.

Supports all ref types: callback refs, mutable ref objects, and null/undefined.

Example

const MyComponent = React.forwardRef<HTMLDivElement, Props>((props, forwardedRef) => {
const internalRef = useRef<HTMLDivElement>(null);
const mergedRef = useMergedRefs(forwardedRef, internalRef);

return <div ref={mergedRef}>Content</div>;
});
// was this page useful?