Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

persistQueryClient.md

288 lines10.3 KB

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)
11- [createAsyncStoragePersister](../createAsyncStoragePersister)
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 (see [more](https://developer.mozilla.org/en-US/docs/Web/API/setTimeout#maximum_delay_value)).
25​
26```tsx
27const queryClient = new QueryClient({
28 defaultOptions: {
29 queries: {
30 gcTime: 1000 * 60 * 60 * 24, // 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`](../../reference/hydration#dehydrate) 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`](../../reference/hydration#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 = 1000 * 60 * 60 * 24, // 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 = 1000 * 60 * 60 * 24, // 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
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/QueryClientProvider):
184​
185```tsx
186import { PersistQueryClientProvider } from '@tanstack/react-query-persist-client'
187import { createSyncStoragePersister } from '@tanstack/query-sync-storage-persister'
188​
189const queryClient = new QueryClient({
190 defaultOptions: {
191 queries: {
192 gcTime: 1000 * 60 * 60 * 24, // 24 hours
193 },
194 },
195})
196​
197const persister = createSyncStoragePersister({
198 storage: window.localStorage,
199})
200​
201ReactDOM.createRoot(rootElement).render(
202 <PersistQueryClientProvider
203 client={queryClient}
204 persistOptions={{ persister }}
205 >
206 <App />
207 </PersistQueryClientProvider>,
209```
210​
211#### Props
212​
213`PersistQueryClientProvider` takes the same props as [QueryClientProvider](../../reference/QueryClientProvider), 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/QueryClient/#queryclientresumepausedmutations)
221 - if a Promise is returned, it will be awaited; restoring is seen as ongoing until then
222​
223### useIsRestoring
224​
225If 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.
226​
227## Persisters
228​
229### Persisters Interface
230​
231Persisters have the following interfaces:
232​
233```tsx
234export interface Persister {
235 persistClient(persistClient: PersistedClient): Promisable<void>
236 restoreClient(): Promisable<PersistedClient | undefined>
237 removeClient(): Promisable<void>
239```
240​
241Persisted Client entries have the following interface:
242​
243```tsx
244export interface PersistedClient {
245 timestamp: number
246 buster: string
247 cacheState: any
249```
250​
251You can import these (to build a persister):
252​
253```tsx
254import {
255 PersistedClient,
256 Persister,
257} from '@tanstack/react-query-persist-client'
258```
259​
260### Building A Persister
261​
262You 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`.
263​
264```tsx
265import { get, set, del } from 'idb-keyval'
266import {
267 PersistedClient,
268 Persister,
269} from '@tanstack/react-query-persist-client'
270​
271/**
272 * Creates an Indexed DB persister
273 * @see https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API
274 */
275export function createIDBPersister(idbValidKey: IDBValidKey = 'reactQuery') {
276 return {
277 persistClient: async (client: PersistedClient) => {
278 await set(idbValidKey, client)
279 },
280 restoreClient: async () => {
281 return await get<PersistedClient>(idbValidKey)
282 },
283 removeClient: async () => {
284 await del(idbValidKey)
285 },
286 } satisfies Persister
288```