# useMergedRefs

> Combines several refs into one memoized callback ref.

`useMergedRefs` combines up to four refs into a single callback ref, so a component can keep its own ref to an element while forwarding the caller's ref to the same element. It is `useMergedRefs` from `@base-ui/utils`, re-exported through a Dify UI subpath.

```tsx
import { useMergedRefs } from '@langgenius/dify-ui/use-merged-refs'
```

## Usage guidelines

- **Use it when a component needs the element and the caller passes a ref**: the internal ref and the caller's `ref` both receive the same element.
- **Pass object refs, callback refs or nothing**: `null` and `undefined` entries are skipped. When every entry is empty, the hook returns `null`.
- **Rely on callback-ref cleanup**: a callback ref that returns a cleanup function has it called when the element detaches or the merged refs change.
- **Do not merge refs for a `render` element or `useRender`**: Base UI parts and [`useRender`](/utilities/use-render.md) already merge their `ref` with the `render` element's ref.
- **Skip it when one ref is enough**: forward the caller's `ref` directly when the component does not read the element itself.

Each input ref may be a React ref, `null` or `undefined`. The result is a callback ref or `null`.

The returned callback stays the same while the refs passed in are the same, so the element is not detached and reattached on every render.

## Examples

### Focus a forwarded input from a shortcut

The component needs the element for the `/` shortcut, and the caller's `ref` still receives the same input.

```tsx
import { useMergedRefs } from '@langgenius/dify-ui/use-merged-refs'
import * as React from 'react'

function SearchField({ ref, ...props }: React.ComponentProps<'input'>) {
  const inputRef = React.useRef<HTMLInputElement>(null)
  const mergedRef = useMergedRefs(inputRef, ref)

  React.useEffect(() => {
    function handleKeyDown(event: KeyboardEvent) {
      if (event.key !== '/' || event.target !== document.body) return
      event.preventDefault()
      inputRef.current?.focus()
    }

    document.addEventListener('keydown', handleKeyDown)
    return () => document.removeEventListener('keydown', handleKeyDown)
  }, [])

  return <input ref={mergedRef} type="search" {...props} />
}
```

## API reference

### useMergedRefs

Merges refs into a single memoized callback ref or `null`. This makes sure multiple refs are updated together and have the same value.

This function accepts up to four refs.

```ts
useMergedRefs<I>(a: InputRef<I>, b: InputRef<I>): Result<I>

useMergedRefs<I>(
  a: InputRef<I>,
  b: InputRef<I>,
  c: InputRef<I>,
): Result<I>

useMergedRefs<I>(
  a: InputRef<I>,
  b: InputRef<I>,
  c: InputRef<I>,
  d: InputRef<I>,
): Result<I>
```

**Shared parameters**

| Parameter | Type          | Description |
| --------- | ------------- | ----------- |
| `a`       | `InputRef<I>` | —           |
| `b`       | `InputRef<I>` | —           |

**Returns:** `Result<I>`
