useMergedRef
Hook to merge multiple refs into one.
Demo
INFO
The component has a ref to change border color of a div element when a button is clicked and use useResizeObserver hook to observe the size of div element to check when its width is less of 100px. Since useResizeObserver works with a ref attached to an element, there are two ref that will be attached to the div element. So it has been used useMergedRef hook to merge refs.
Loading demo…
Show source code
tsx
import { useCallback, useRef, useState } from "react";
import { useMergedRef, useResizeObserver } from "../../../..";
export const UseMergedRef = () => {
const [state, setState] = useState(false);
const { ref: refCb } = useResizeObserver<HTMLDivElement>(
useCallback((entries: ResizeObserverEntry[]) => {
const result = entries[0].contentRect.width < 100;
result !== state && setState(result);
}, [state]),
{ mode: "ref" }
);
const ref = useRef<HTMLDivElement>(null);
const mergedRef = useMergedRef<HTMLDivElement>(ref, refCb);
const changeBorderColor = () => {
ref.current && (ref.current.style.border = ref.current.style.border.indexOf("lightgray") !== -1
? '1px solid darkcyan'
: '1px solid lightgray'
);
}
return <div>
<p>{"Has width < 100 px: " + state}</p>
<div ref={mergedRef} style={{border: '1px solid lightgray', width: 150, height: 200, resize: "both", overflow: 'auto'}}></div>
<br />
<button onClick={changeBorderColor}>Change border color</button>
</div>
}Types
UseMergedRefProps
@templateT - The element or value type that all refs point to.
Parameters accepted by useMergedRef.
| Property | Type | Required | Description |
|---|---|---|---|
refs | Ref<T>[] | ✓ | A variadic list of React refs to merge. Each entry may be a RefCallback<T>, a MutableRefObject<T>, or null. When the merged ref is set, all provided refs are updated simultaneously with the same value, allowing multiple consumers to observe the same DOM element or imperative handle. |
UseMergedRefResult
@templateT - The element or value type that the merged ref points to.
Return value of useMergedRef.
A single stable {@link Ref} that, when attached to a JSX element, forwards the resolved value to every ref passed as input. Compatible with both ref props on DOM elements and forwardRef patterns.
ts
export type UseMergedRefResult<T> = Ref<T>;