Open History to see the last commit
1---
2id: createPersister
3title: experimental_createPersister
4---
5β
6## Installation
7β
8This utility comes as a separate package and is available under the `'@tanstack/query-persist-client-core'` import.
9β
10```bash
11npm install @tanstack/query-persist-client-core
12```
13β
14or
15β
16```bash
17pnpm add @tanstack/query-persist-client-core
18```
19β
20or
21β
22```bash
23yarn add @tanstack/query-persist-client-core
24```
25β
26or
27β
28```bash
29bun add @tanstack/query-persist-client-core
30```
31β
32> Note: This util is also included in the `@tanstack/react-query-persist-client` package, so you do not need to install it separately if you are using that package.
33β
34## Usage
35β
36- Import the `experimental_createPersister` function
37- Create a new `experimental_createPersister`
38 - you can pass any `storage` to it that adheres to the `AsyncStorage` or `Storage` interface - the example below uses the async-storage from React Native.
39- Pass that `persister` as an option to your Query. This can be done either by passing it to the `defaultOptions` of the `QueryClient` or to any `useQuery` hook instance.
40 - If you pass this `persister` as `defaultOptions`, all queries will be persisted to the provided `storage`. You can additionally narrow this down by passing `filters`. In contrast to the `persistClient` plugin, this will not persist the whole query client as a single item, but each query separately. As a key, the query hash is used.
41 - If you provide this `persister` to a single `useQuery` hook, only this Query will be persisted.
42- Note: `queryClient.setQueryData()` operations are not persisted, this means that if you perform an optimistic update and refresh the page before the query has been invalidated, your changes to the query data will be lost. See https://github.com/TanStack/query/issues/6310
43β
44This way, you do not need to store whole `QueryClient`, but choose what is worth to be persisted in your application. Each query is lazily restored (when the Query is first used) and persisted (after each run of the `queryFn`), so it does not need to be throttled. `staleTime` is also respected after restoring the Query, so if data is considered `stale`, it will be refetched immediately after restoring. If data is `fresh`, the `queryFn` will not run.
45β
46Garbage collecting a Query from memory **does not** affect the persisted data. That means Queries can be kept in memory for a shorter period of time to be more **memory efficient**. If they are used the next time, they will just be restored from the persistent storage again.
47β
48```tsx
49import AsyncStorage from '@react-native-async-storage/async-storage'
50import { QueryClient } from '@tanstack/react-query'
51import { experimental_createPersister } from '@tanstack/query-persist-client-core'
52β
53const queryClient = new QueryClient({
54 defaultOptions: {
55 queries: {
56 gcTime: 1000 * 30, // 30 seconds
57 persister: experimental_createPersister({
58 storage: AsyncStorage,
59 maxAge: 1000 * 60 * 60 * 12, // 12 hours
60 }),
61 },
62 },
63})
64```
65β
66### Adapted defaults
67β
68The `createPersister` plugin technically wraps the `queryFn`, so it doesn't restore if the `queryFn` doesn't run. In that way, it acts as a caching layer between the Query and the network. Thus, the `networkMode` defaults to `'offlineFirst'` when a persister is used, so that restoring from the persistent storage can also happen even if there is no network connection.
69β
70## API
71β
72### `experimental_createPersister`
73β
74```tsx
75experimental_createPersister(options: StoragePersisterOptions)
76```
77β
78#### `Options`
79β
80```tsx
81export interface StoragePersisterOptions {
82 /** The storage client used for setting and retrieving items from cache.
83 * For SSR pass in `undefined`.
84 */
85 storage: AsyncStorage | Storage | undefined | null
86 /**
87 * How to serialize the data to storage.
88 * @default `JSON.stringify`
89 */
90 serialize?: (persistedQuery: PersistedQuery) => string
91 /**
92 * How to deserialize the data from storage.
93 * @default `JSON.parse`
94 */
95 deserialize?: (cachedString: string) => PersistedQuery
96 /**
97 * A unique string that can be used to forcefully invalidate existing caches,
98 * if they do not share the same buster string
99 */
100 buster?: string
101 /**
102 * The max-allowed age of the cache in milliseconds.
103 * If a persisted cache is found that is older than this
104 * time, it will be discarded
105 * @default 24 hours
106 */
107 maxAge?: number
108 /**
109 * Prefix to be used for storage key.
110 * Storage key is a combination of prefix and query hash in a form of `prefix-queryHash`.
111 */
112 prefix?: string
113 /**
114 * Filters to narrow down which Queries should be persisted.
115 */
116 filters?: QueryFilters
117}
118β
119interface AsyncStorage {
120 getItem: (key: string) => Promise<string | undefined | null>
121 setItem: (key: string, value: string) => Promise<unknown>
122 removeItem: (key: string) => Promise<void>
123}
124```
125β
126The default options are:
127β
128```tsx
129{
130 prefix = 'tanstack-query',
131 maxAge = 1000 * 60 * 60 * 24,
132 serialize = JSON.stringify,
133 deserialize = JSON.parse,
134}
135```