# 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

```ts
import { useMergedRefs } from '@vincent.ri/react-tils'
// or only this hook
import { useMergedRefs } from '@vincent.ri/react-tils/useMergedRefs'
```

## Usage

```ts
function Section({ ref }: { ref?: Ref<HTMLElement> }) {
  const [inViewRef, inView] = useInView<HTMLElement>()
  const [sizeRef, { width }] = useElementSize<HTMLElement>()
  return <section ref={useMergedRefs(ref, inViewRef, sizeRef)}>…</section>
}
```

## 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

```ts
function useMergedRefs<T>(...refs: (Ref<T> | undefined)[]): (element: T | null) => void
```

| Parameter | Description |
| --- | --- |
| `refs` | The refs to set. |

## Browser support

Works in all modern browsers.

## Coming from another library?

Other libraries call this `useMergeRefs`, `useForkRef`, `mergeRefs`.

---

315 B minified and brotlied
Source: https://github.com/vincentri/react-tils/blob/main/src/useMergedRefs.ts
Docs page: https://vincentri.github.io/react-tils/hooks/useMergedRefs/
Previous: [useStickToBottom](https://vincentri.github.io/react-tils/hooks/useStickToBottom.md)
Next: [useLocalStorage](https://vincentri.github.io/react-tils/hooks/useLocalStorage.md)
