Skip to content

once

once<T>(fn): T

Defined in: functions/once/index.ts:26

Creates a version of a function that runs only once. Subsequent calls return the cached result from the first invocation and ignore any new arguments.

T extends (…args) => unknown

T

The function to wrap

T

A wrapped function that executes fn at most once

const init = once(() => ({ id: Math.random() }));
const a = init();
const b = init();
a === b; // true

run once, single call, memoize no args, lazy init, singleton

Error if fn is not a function

The reference to fn is released after the first call so it can be garbage-collected. If fn throws on the first call, the exception propagates and subsequent calls return undefined without retrying.