All hooks / Elements
useMergedRefs
Combines several refs into one callback ref, so one element can have a useRef, a forwarded ref prop, and refs from hooks such as useInView and useElementSize at the same time.
Accepts ref objects, callback refs, null, and undefined. The merged ref never changes; when one of the refs changes, the element moves to the new ref right after render. Works with React 18, with React 19 callback refs that return a cleanup function, and with React Compiler.
Import
import { useMergedRefs } from '@vincent.ri/react-tils'
// or only this hook
import { useMergedRefs } from '@vincent.ri/react-tils/useMergedRefs'Usage
function Section({ ref }: { ref?: Ref<HTMLElement> }) {
const [inViewRef, inView] = useInView<HTMLElement>()
const [sizeRef, { width }] = useElementSize<HTMLElement>()
return <section ref={useMergedRefs(ref, inViewRef, sizeRef)}>…</section>
}Live demo
Three refs on one box: useInView, useElementSize, useRef.
When to use it
Two or more refs must point at the same element.
When not to
There is only one ref; pass it directly.
API
function useMergedRefs<T>(...refs: (Ref<T> | undefined)[]): (element: T | null) => void| Parameter | Description |
|---|---|
refs | The refs to set. |
Browser support
Uses only long-established browser features, so it works wherever React does.
First version with support, from MDN's compatibility data (web-features 3.42.0, @mdn/browser-compat-data 8.1.5).
Coming from another library?
Other libraries call this useMergeRefs, useForkRef, mergeRefs.