# useRefWithInit

> A ref whose initial value comes from a function called once.

`useRefWithInit` works like `React.useRef`, but computes the initial value with a function on the first render only. It is `useRefWithInit` from `@base-ui/utils`, re-exported through a Dify UI subpath.

```tsx
import { useRefWithInit } from '@langgenius/dify-ui/use-ref-with-init'
```

## Usage guidelines

- **Use it for an instance that is expensive or must be created once**: a store, a `Map` or `Set` of registered elements, or a set of pending timeout IDs. `React.useRef(new Map())` builds a new value on every render and throws it away.
- **Pass an argument instead of a closure**: the optional second argument is passed to the initializer, so a module-level factory such as `createStore` needs no inline wrapper.
- **Do not expect it to react to changes**: later changes to the initializer or its argument do not reset the ref. Use state or a keyed remount when the value depends on props that change.
- **Keep the initializer safe to retry or discard**: it runs during render, so it must not subscribe, start timers or cause other side effects.
- **Use `React.useRef` for a cheap initial value**: a literal such as `null`, `0` or `false` does not need an initializer.

## Examples

### Registry of elements

```tsx
import { useRefWithInit } from '@langgenius/dify-ui/use-ref-with-init'

function useHandleRegistry() {
  const handlesRef = useRefWithInit(() => new Map<number, HTMLButtonElement>())

  function register(index: number, element: HTMLButtonElement | null) {
    if (element) handlesRef.current.set(index, element)
    else handlesRef.current.delete(index)
  }

  return { handlesRef, register }
}
```

### Store created from a factory

```tsx
const storeRef = useRefWithInit(createDataSourceStore)
```

## API reference

### useRefWithInit

A React.useRef() that is initialized with a function. Note that it accepts an optional initialization argument, so the initialization function doesn't need to be an inline closure.

```ts
useRefWithInit<T>(init: () => T): React.RefObject<T>

useRefWithInit<T, U>(
  init: (arg: U) => T,
  initArg: U,
): React.RefObject<T>
```

**Returns:** `React.RefObject<T>`
