useMemoize

A React Hook that return a function that memoize value (return same memoized value for same arguments).

Demo

Try to click multiple times to fetch, you will see that the first fetch will actually fetch data, but the rest will return the memoized value.

Source

Usage

See API for more details.

Source

Click links below to view source on GitHub.

API

const cachedFn = useMemoize(fnToBeCached, options)

FnToBeCached

The function that will be memoized.

Options

export type UseMemoizeCache<Key, Value> = { get: (key: Key) => Value | undefined set: (key: Key, value: Value) => void has: (key: Key) => boolean delete: (key: Key) => void clear(): void } export type UseMemoizeOptions<Result, Args extends unknown[]> = { /** * Custom cache key generator * * @defaultValue JSON.stringify(args) */ getKey?: (...args: Args) => string | number /** * Custom cache, can be a Map or other object that implements the cache interface * * @defaultValue new Map() */ cache?: UseMemoizeCache<CacheKey, Result> }

Returns

export type UseMemoizeReturns<Result, Args extends unknown[]> = { /** * Memoized function */ (...args: Args): Result /** * Load data and replace the cache with the new value */ load: (...args: Args) => Result /** * Delete cache by args */ delete: (...args: Args) => void /** * Clear all cache */ clear(): void /** * Get cache key by args */ getKey: (...args: Args) => CacheKey /** * A map-like cache object, you can use it to manipulate the cache directly */ cache: UseMemoizeCache<CacheKey, Result> }