Loading source
Pulling the file list, source metadata, and syntax-aware rendering for this listing.
Source from repo
Apply VueUse composables in Vue 3/Nuxt projects to replace custom implementations with battle-tested utilities.
Files
Skill
Size
Entrypoint
Format
Open file
Syntax-highlighted preview of this file as included in the skill package.
references/useMemoize.md
1---2category: Utilities3---45# useMemoize67Cache results of functions depending on arguments and keep it reactive. It can also be used for asynchronous functions and will reuse existing promises to avoid fetching the same data at the same time.89::: tip10The results are not cleared automatically. Call `clear()` in case you no longer need the results or use own caching mechanism to avoid memory leaks.11:::1213## Usage1415```ts16import { useMemoize } from '@vueuse/core'1718const getUser = useMemoize(19async (userId: number): Promise<UserData> =>20axios.get(`users/${userId}`).then(({ data }) => data),21)2223const user1 = await getUser(1) // Request users/124const user2 = await getUser(2) // Request users/225// ...26const user1 = await getUser(1) // Retrieve from cache2728// ...29const user1 = await getUser.load(1) // Request users/13031// ...32getUser.delete(1) // Delete cache from user 133getUser.clear() // Clear full cache34```3536Combine with `computed` or `computedAsync` to achieve reactivity:3738```ts39import { computedAsync, useMemoize } from '@vueuse/core'4041const getUser = useMemoize(42async (userId: number): Promise<UserData> =>43axios.get(`users/${userId}`).then(({ data }) => data),44)45// ---cut---46const user1 = computedAsync(() => getUser(1))47// ...48await getUser.load(1) // Will also update user149```5051### Resolving cache key5253The key for caching is determined by the arguments given to the function and will be serialized by default with `JSON.stringify`.54This will allow equal objects to receive the same cache key. In case you want to customize the key you can pass `getKey`5556::: warning Performance Consideration57Using `JSON.stringify` as the default key generator can be **slow for large or complex objects**. For better performance with complex arguments, it's highly recommended to provide a custom `getKey` function that generates keys based on primitive values or unique identifiers.58:::5960#### Basic Example6162```ts63import { useMemoize } from '@vueuse/core'64// ---cut---65const getUser = useMemoize(66async (userId: number, headers: AxiosRequestHeaders): Promise<UserData> =>67axios.get(`users/${userId}`, { headers }).then(({ data }) => data),68{69// Use only userId to get/set cache and ignore headers70getKey: (userId, headers) => userId,71},72)73```7475### Customize cache mechanism7677By default, the results are cached within a `Map`. You can implement your own mechanism by passing `cache` as options with following structure:7879```ts80export interface MemoizeCache<Key, Value> {81/**82* Get value for key83*/84get: (key: Key) => Value | undefined85/**86* Set value for key87*/88set: (key: Key, value: Value) => void89/**90* Return flag if key exists91*/92has: (key: Key) => boolean93/**94* Delete value for key95*/96delete: (key: Key) => void97/**98* Clear cache99*/100clear: () => void101}102```103104## Type Declarations105106```ts107type CacheKey = any108/**109* Custom memoize cache handler110*/111export interface UseMemoizeCache<Key, Value> {112/**113* Get value for key114*/115get: (key: Key) => Value | undefined116/**117* Set value for key118*/119set: (key: Key, value: Value) => void120/**121* Return flag if key exists122*/123has: (key: Key) => boolean124/**125* Delete value for key126*/127delete: (key: Key) => void128/**129* Clear cache130*/131clear: () => void132}133/**134* Memoized function135*/136export interface UseMemoizeReturn<Result, Args extends unknown[]> {137/**138* Get result from cache or call memoized function139*/140(...args: Args): Result141/**142* Call memoized function and update cache143*/144load: (...args: Args) => Result145/**146* Delete cache of given arguments147*/148delete: (...args: Args) => void149/**150* Clear cache151*/152clear: () => void153/**154* Generate cache key for given arguments155*/156generateKey: (...args: Args) => CacheKey157/**158* Cache container159*/160cache: UseMemoizeCache<CacheKey, Result>161}162export interface UseMemoizeOptions<Result, Args extends unknown[]> {163getKey?: (...args: Args) => string | number164cache?: UseMemoizeCache<CacheKey, Result>165}166/**167* Reactive function result cache based on arguments168*169* @__NO_SIDE_EFFECTS__170*/171export declare function useMemoize<Result, Args extends unknown[]>(172resolver: (...args: Args) => Result,173options?: UseMemoizeOptions<Result, Args>,174): UseMemoizeReturn<Result, Args>175```176