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
Usage guidelines
- Use it for an instance that is expensive or must be created once: a store, a
MaporSetof 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
createStoreneeds 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.useReffor a cheap initial value: a literal such asnull,0orfalsedoes not need an initializer.
Examples
Registry of elements
tsx
Store created from a factory
tsx
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.
Returns
React.RefObject<T>