Open History to see the last commit
1---
2id: persistQueryClient
3title: persistQueryClient
4---
5β
6This is set of utilities for interacting with "persisters" which save your queryClient for later use. Different **persisters** can be used to store your client and cache to many different storage layers.
7β
8## Build Persisters
9β
10- [createSyncStoragePersister](./createSyncStoragePersister.md)
11- [createAsyncStoragePersister](./createAsyncStoragePersister.md)
12- [create a custom persister](#persisters)
13β
14## How It Works
15β
16**IMPORTANT** - for persist to work properly, you probably want to pass `QueryClient` a `gcTime` value to override the default during hydration (as shown above).
17β
18If it is not set when creating the `QueryClient` instance, it will default to `300000` (5 minutes) for hydration, and the stored cache will be discarded after 5 minutes of inactivity. This is the default garbage collection behavior.
19β
20It should be set as the same value or higher than persistQueryClient's `maxAge` option. E.g. if `maxAge` is 24 hours (the default) then `gcTime` should be 24 hours or higher. If lower than `maxAge`, garbage collection will kick in and discard the stored cache earlier than expected.
21β
22You can also pass it `Infinity` to disable garbage collection behavior entirely.
23β
24Due to a JavaScript limitation, the maximum allowed `gcTime` is about [24 days](https://developer.mozilla.org/en-US/docs/Web/API/setTimeout#maximum_delay_value), although it is possible to work around this limit using [timeoutManager.setTimeoutProvider](../reference/interfaces/TimeoutManager.md#settimeoutprovider).
25β
26```tsx
27const queryClient = new QueryClient({
28 defaultOptions: {
29 queries: {
30 gcTime: 24 * 60 * 60 * 1000, // 24 hours
31 },
32 },
33})
34```
35β
36### Cache Busting
37β
38Sometimes you may make changes to your application or data that immediately invalidate any and all cached data. If and when this happens, you can pass a `buster` string option. If the cache that is found does not also have that buster string, it will be discarded. The following several functions accept this option:
39β
40```tsx
41persistQueryClient({ queryClient, persister, buster: buildHash })
42persistQueryClientSave({ queryClient, persister, buster: buildHash })
43persistQueryClientRestore({ queryClient, persister, buster: buildHash })
44```
45β
46### Removal
47β
48If data is found to be any of the following:
49β
501. expired (see `maxAge`)
512. busted (see `buster`)
523. error (ex: `throws ...`)
534. empty (ex: `undefined`)
54β
55the persister `removeClient()` is called and the cache is immediately discarded.
56β
57## API
58β
59### `persistQueryClientSave`
60β
61- Your query/mutation are `dehydrated` and stored by the persister you provided.
62- `createSyncStoragePersister` and `createAsyncStoragePersister` throttle this action to happen at most every 1 second to save on potentially expensive writes. Review their documentation to see how to customize their throttle timing.
63β
64You can use this to explicitly persist the cache at the moment(s) you choose.
65β
66```tsx
67persistQueryClientSave({
68 queryClient,
69 persister,
70 buster = '',
71 dehydrateOptions = undefined,
72})
73```
74β
75### `persistQueryClientSubscribe`
76β
77Runs `persistQueryClientSave` whenever the cache changes for your `queryClient`. For example: you might initiate the `subscribe` when a user logs-in and checks "Remember me".
78β
79- It returns an `unsubscribe` function which you can use to discontinue the monitor; ending the updates to the persisted cache.
80- If you want to erase the persisted cache after the `unsubscribe`, you can send a new `buster` to `persistQueryClientRestore` which will trigger the persister's `removeClient` function and discard the persisted cache.
81β
82```tsx
83persistQueryClientSubscribe({
84 queryClient,
85 persister,
86 buster = '',
87 dehydrateOptions = undefined,
88})
89```
90β
91### `persistQueryClientRestore`
92β
93- Attempts to `hydrate` a previously persisted dehydrated query/mutation cache from the persister back into the query cache of the passed query client.
94- If a cache is found that is older than the `maxAge` (which by default is 24 hours), it will be discarded. This timing can be customized as you see fit.
95β
96You can use this to restore the cache at moment(s) you choose.
97β
98```tsx
99persistQueryClientRestore({
100 queryClient,
101 persister,
102 maxAge = 24 * 60 * 60 * 1000, // 24 hours
103 buster = '',
104 hydrateOptions = undefined,
105})
106```
107β
108### `persistQueryClient`
109β
110Takes the following actions:
111β
1121. Immediately restores any persisted cache ([see `persistQueryClientRestore`](#persistqueryclientrestore))
1132. Subscribes to the query cache and returns the `unsubscribe` function ([see `persistQueryClientSubscribe`](#persistqueryclientsubscribe)).
114β
115This functionality is preserved from version 3.x.
116β
117```tsx
118persistQueryClient({
119 queryClient,
120 persister,
121 maxAge = 24 * 60 * 60 * 1000, // 24 hours
122 buster = '',
123 hydrateOptions = undefined,
124 dehydrateOptions = undefined,
125})
126```
127β
128### `Options`
129β
130All options available are as follows:
131β
132```tsx
133interface PersistQueryClientOptions {
134 /** The QueryClient to persist */
135 queryClient: QueryClient
136 /** The Persister interface for storing and restoring the cache
137 * to/from a persisted location */
138 persister: Persister
139 /** The max-allowed age of the cache in milliseconds.
140 * If a persisted cache is found that is older than this
141 * time, it will be **silently** discarded
142 * (defaults to 24 hours) */
143 maxAge?: number
144 /** A unique string that can be used to forcefully
145 * invalidate existing caches if they do not share the same buster string */
146 buster?: string
147 /** The options passed to the hydrate function
148 * Not used on `persistQueryClientSave` or `persistQueryClientSubscribe` */
149 hydrateOptions?: HydrateOptions
150 /** The options passed to the dehydrate function
151 * Not used on `persistQueryClientRestore` */
152 dehydrateOptions?: DehydrateOptions
153}
154```
155β
156There are actually three interfaces available:
157β
158- `PersistedQueryClientSaveOptions` is used for `persistQueryClientSave` and `persistQueryClientSubscribe` (doesn't use `hydrateOptions`).
159- `PersistedQueryClientRestoreOptions` is used for `persistQueryClientRestore` (doesn't use `dehydrateOptions`).
160- `PersistQueryClientOptions` is used for `persistQueryClient`
161β
162## Usage with React
163β
164[persistQueryClient](#persistQueryClient) will try to restore the cache and automatically subscribes to further changes, thus syncing your client to the provided storage.
165β
166However, restoring is asynchronous, because all persisters are async by nature, which means that if you render your App while you are restoring, you might get into race conditions if a query mounts and fetches at the same time.
167β
168Further, if you subscribe to changes outside of the React component lifecycle, you have no way of unsubscribing:
169β
170```tsx
171// π¨ never unsubscribes from syncing
172persistQueryClient({
173 queryClient,
174 persister: localStoragePersister,
175})
176β
177// π¨ happens at the same time as restoring
178ReactDOM.createRoot(rootElement).render(<App />)
179```
180β
181### PersistQueryClientProvider
182β
183For this use-case, you can use the `PersistQueryClientProvider`. It will make sure to subscribe / unsubscribe correctly according to the React component lifecycle, and it will also make sure that queries will not start fetching while we are still restoring. Queries will still render though, they will just be put into `fetchingState: 'idle'` until data has been restored. Then, they will refetch unless the restored data is _fresh_ enough, and _initialData_ will also be respected. It can be used _instead of_ the normal [QueryClientProvider](../reference/functions/QueryClientProvider.md):
184β
185```tsx
186import { PersistQueryClientProvider } from '@tanstack/react-query-persist-client'
187import { createAsyncStoragePersister } from '@tanstack/query-async-storage-persister'
188β
189const queryClient = new QueryClient({
190 defaultOptions: {
191 queries: {
192 gcTime: 24 * 60 * 60 * 1000, // 24 hours
193 },
194 },
195})
196β
197const persister = createAsyncStoragePersister({
198 storage: window.localStorage,
199})
200β
201ReactDOM.createRoot(rootElement).render(
202 <PersistQueryClientProvider
203 client={queryClient}
204 persistOptions={{ persister }}
205 >
206 <App />
207 </PersistQueryClientProvider>,
208)
209```
210β
211#### Props
212β
213`PersistQueryClientProvider` takes the same props as [QueryClientProvider](../reference/functions/QueryClientProvider.md), and additionally:
214β
215- `persistOptions: PersistQueryClientOptions`
216 - all [options](#options) you can pass to [persistQueryClient](#persistqueryclient) minus the QueryClient itself
217- `onSuccess?: () => Promise<unknown> | unknown`
218 - optional
219 - will be called when the initial restore is finished
220 - can be used to [resumePausedMutations](../reference/classes/QueryClient.md#resumepausedmutations)
221 - if a Promise is returned, it will be awaited; restoring is seen as ongoing until then
222- `onError?: () => Promise<unknown> | unknown`
223 - optional
224 - will be called when an error is thrown during restoration
225 - if a Promise is returned, it will be awaited
226β
227### useIsRestoring
228β
229If you are using the `PersistQueryClientProvider`, you can also use the `useIsRestoring` hook alongside it to check if a restore is currently in progress. `useQuery` and friends also check this internally to avoid race conditions between the restore and mounting queries.
230β
231## Persisters
232β
233### Persisters Interface
234β
235Persisters have the following interfaces:
236β
237```tsx
238export interface Persister {
239 persistClient(persistClient: PersistedClient): Promisable<void>
240 restoreClient(): Promisable<PersistedClient | undefined>
241 removeClient(): Promisable<void>
242}
243```
244β
245Persisted Client entries have the following interface:
246β
247```tsx
248export interface PersistedClient {
249 timestamp: number
250 buster: string
251 clientState: DehydratedState
252}
253```
254β
255You can import these (to build a persister):
256β
257```tsx
258import {
259 PersistedClient,
260 Persister,
261} from '@tanstack/react-query-persist-client'
262```
263β
264### Building A Persister
265β
266You can persist however you like. Here is an example of how to build an [Indexed DB](https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API) persister. Compared to `Web Storage API`, Indexed DB is faster, stores more than 5MB, and doesn't require serialization. That means it can readily store Javascript native types, such as `Date` and `File`.
267β
268```tsx
269import { get, set, del } from 'idb-keyval'
270import {
271 PersistedClient,
272 Persister,
273} from '@tanstack/react-query-persist-client'
274β
275/**
276 * Creates an Indexed DB persister
277 * @see https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API
278 */
279export function createIDBPersister(idbValidKey: IDBValidKey = 'reactQuery') {
280 return {
281 persistClient: async (client: PersistedClient) => {
282 await set(idbValidKey, client)
283 },
284 restoreClient: async () => {
285 return await get<PersistedClient>(idbValidKey)
286 },
287 removeClient: async () => {
288 await del(idbValidKey)
289 },
290 } satisfies Persister
291}
292```