R
fn

useMemoize

v0.0.15testeddemo

Cache the result of a (possibly async) function by its arguments, exposing a reactive cache and explicit `load`/`delete`/`clear`/`generateKey` controls. When no custom `cache` is supplied the default `Map` path delegates to `@robonen/stdlib`'s `memoize` for the get-or-compute core and is wrapped in `shallowReactive` so cache reads inside effects stay live. A custom cache backend (e.g. an LRU) can be plugged in via `options.cache`. SSR-safe: no browser globals are touched.

Examples

ts
const getUser = useMemoize(async (id: number) => fetch(`/users/${id}`).then(r => r.json()));
const a = await getUser(1); // network call
const b = await getUser(1); // cached, same promise
await getUser.load(1);      // force refresh
getUser.delete(1);          // evict one
getUser.clear();            // evict all
ts
// Custom key + reactive cache size in a computed
const square = useMemoize((n: number) => n * n, { getKey: n => n });
const size = computed(() => (square.cache as Map<number, number>).size);

Demo

Loading demo…

Signature

ts
export function useMemoize<Result, Args extends unknown[]>(
  resolver: (...args: Args) => Result,
  options?: UseMemoizeOptions<Result, Args>,
): UseMemoizeReturn<Result, Args>{ ... }

Type Parameters

Result
Argsextends unknown[]

Parameters

ParameterTypeDescription
resolver(...args: Args) => ResultThe function whose results are cached (sync or async)
options?UseMemoizeOptions<Result, Args> | undefinedCustom `getKey` and/or `cache` backend

Returns

UseMemoizeReturn<Result, Args>A callable memoized function with `load`, `delete`, `clear`, `generateKey`, and the reactive `cache`