useMergeRefs
Sends one ref value to any number of mutable or callback refs.
About
useMergeRefs combines several refs when one element must be observed by multiple hooks or consumers.
Example
import { useRef } from "react";
import { useEventListenerRef, useMergeRefs } from "rooks";
export default function FocusableClickTarget() {
const inputRef = useRef<HTMLInputElement | null>(null);
const clickRef = useEventListenerRef("click", () => {
console.log("Input clicked");
});
const mergedRef = useMergeRefs(inputRef, clickRef);
return (
<div>
<input ref={mergedRef} aria-label="Tracked input" />
<button type="button" onClick={() => inputRef.current?.focus()}>
Focus input
</button>
</div>
);
}Parameters
...refs: Array<PossibleRef<T>>— any number of mutable refs, callback refs,null, orundefinedvalues.
Return value
Returns a callback ref that assigns the same element or null to each input ref in order. It returns null only when every supplied value is exactly null; an empty list also returns null.
Behavior and lifecycle
Because the rest-parameter array is new on every render, the current implementation also creates a new merged callback each render. React consequently detaches the old callback with null and attaches the new callback with the element. Callback errors are not caught; an exception stops later refs from being assigned.
Compatibility and accessibility
The hook is SSR-safe and runs assignments only during React ref attachment. Merging refs does not add focusability, keyboard support, or an accessible name to the element.
Related
- useForkRef memoizes a pair of refs and avoids callback churn while those refs remain stable.