useMergedRefs
Point several refs at one node — your component's own ref and the one its caller passed — with React 19 ref cleanups handled.
useMergedRefs combines several refs into one callback ref. Reach for it when a component keeps its own ref to a node, to focus or measure it, and must also forward the ref its caller passed.
import { useMergedRefs } from '@42-central/ui-react';
function ClearableInput({ ref, ...props }: ComponentProps<'input'>) {
const inputRef = useRef<HTMLInputElement>(null);
const mergedRef = useMergedRefs(inputRef, ref);
return <input ref={mergedRef} {...props} />;
}The kit's own components merge refs this way, so a form library that focuses a field on error through ref keeps working on a kit input.
Usage
The input clears and refocuses itself through its own ref; the parent reads the same node through the ref it passed.
Nothing read yet.
Code
function ClearableInput({ ref, ...props }) {
const inputRef = useRef(null);
const mergedRef = useMergedRefs(inputRef, ref);
// Clear uses inputRef.current
return <input ref={mergedRef} {...props} />;
}
const ref = useRef(null);
<ClearableInput ref={ref} />
<Button onClick={() => setRead(ref.current.value)}>Read through the parent's ref</Button>API
function useMergedRefs<T>(...refs: (Ref<T> | undefined)[]): RefCallback<T>
function mergeRefs<T>(...refs: (Ref<T> | undefined)[]): RefCallback<T>Each ref can be an object ref, a callback ref, null or undefined, so an optional ref prop goes straight in.
The merged ref's identity only changes when one of the refs does. React treats a new callback ref as a different ref and detaches then re-attaches it, so a stable merged ref means your refs aren't reset on every render. A caller who passes an inline callback ref (ref={(node) => …}) still gets a new one per render: that is React's own behaviour for inline callback refs.
Cleanups
The merged ref returns a React 19 cleanup function. When the node detaches, a callback ref that returned its own cleanup has that cleanup run; every other ref (object refs, callback refs that returned nothing) is set back to null. Each ref sees exactly what it would have seen attached on its own.
mergeRefs
mergeRefs is the same merge without the memoization. It returns a new function on every call, so in a component every merged ref would detach and re-attach on each render. Use it outside render, in an imperative helper, or where something else already memoizes the result. In a component, use useMergedRefs.