persistQueryClient

· abundance's blog


This 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.

Build Persisters #

How It Works #

IMPORTANT - for persist to work properly, you probably want to pass QueryClient a gcTime value to override the default during hydration (as shown above).

If 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.

It 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.

You can also pass it Infinity to disable garbage collection behavior entirely.

Due to a Javascript limitation, the maximum allowed gcTime is about 24 days (see more).

1const queryClient = new QueryClient({
2  defaultOptions: {
3    queries: {
4      gcTime: 1000 * 60 * 60 * 24, // 24 hours
5    },
6  },
7})

Cache Busting #

Sometimes 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:

1persistQueryClient({ queryClient, persister, buster: buildHash })
2persistQueryClientSave({ queryClient, persister, buster: buildHash })
3persistQueryClientRestore({ queryClient, persister, buster: buildHash })

Removal #

If data is found to be any of the following:

  1. expired (see maxAge)
  2. busted (see buster)
  3. error (ex: throws ...)
  4. empty (ex: undefined)

the persister removeClient() is called and the cache is immediately discarded.

API #

persistQueryClientSave #

You can use this to explicitly persist the cache at the moment(s) you choose.

1persistQueryClientSave({
2  queryClient,
3  persister,
4  buster = '',
5  dehydrateOptions = undefined,
6})

persistQueryClientSubscribe #

Runs persistQueryClientSave whenever the cache changes for your queryClient. For example: you might initiate the subscribe when a user logs-in and checks "Remember me".

1persistQueryClientSubscribe({
2  queryClient,
3  persister,
4  buster = '',
5  dehydrateOptions = undefined,
6})

persistQueryClientRestore #

You can use this to restore the cache at moment(s) you choose.

1persistQueryClientRestore({
2  queryClient,
3  persister,
4  maxAge = 1000 * 60 * 60 * 24, // 24 hours
5  buster = '',
6  hydrateOptions = undefined,
7})

persistQueryClient #

Takes the following actions:

  1. Immediately restores any persisted cache (see persistQueryClientRestore)
  2. Subscribes to the query cache and returns the unsubscribe function (see persistQueryClientSubscribe).

This functionality is preserved from version 3.x.

1persistQueryClient({
2  queryClient,
3  persister,
4  maxAge = 1000 * 60 * 60 * 24, // 24 hours
5  buster = '',
6  hydrateOptions = undefined,
7  dehydrateOptions = undefined,
8})

Options #

All options available are as follows:

 1interface PersistQueryClientOptions {
 2  /** The QueryClient to persist */
 3  queryClient: QueryClient
 4  /** The Persister interface for storing and restoring the cache
 5   * to/from a persisted location */
 6  persister: Persister
 7  /** The max-allowed age of the cache in milliseconds.
 8   * If a persisted cache is found that is older than this
 9   * time, it will be **silently** discarded
10   * (defaults to 24 hours) */
11  maxAge?: number
12  /** A unique string that can be used to forcefully
13   * invalidate existing caches if they do not share the same buster string */
14  buster?: string
15  /** The options passed to the hydrate function
16   * Not used on `persistQueryClientSave` or `persistQueryClientSubscribe` */
17  hydrateOptions?: HydrateOptions
18  /** The options passed to the dehydrate function
19   * Not used on `persistQueryClientRestore` */
20  dehydrateOptions?: DehydrateOptions
21}

There are actually three interfaces available:

Usage with React #

persistQueryClient will try to restore the cache and automatically subscribes to further changes, thus syncing your client to the provided storage.

However, 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.

Further, if you subscribe to changes outside of the React component lifecycle, you have no way of unsubscribing:

1// 🚨 never unsubscribes from syncing
2persistQueryClient({
3  queryClient,
4  persister: localStoragePersister,
5})
6
7// 🚨 happens at the same time as restoring
8ReactDOM.createRoot(rootElement).render(<App />)

PersistQueryClientProvider #

For 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:

 1import { PersistQueryClientProvider } from '@tanstack/react-query-persist-client'
 2import { createSyncStoragePersister } from '@tanstack/query-sync-storage-persister'
 3
 4const queryClient = new QueryClient({
 5  defaultOptions: {
 6    queries: {
 7      gcTime: 1000 * 60 * 60 * 24, // 24 hours
 8    },
 9  },
10})
11
12const persister = createSyncStoragePersister({
13  storage: window.localStorage,
14})
15
16ReactDOM.createRoot(rootElement).render(
17  <PersistQueryClientProvider
18    client={queryClient}
19    persistOptions={{ persister }}
20  >
21    <App />
22  </PersistQueryClientProvider>,
23)

Props #

PersistQueryClientProvider takes the same props as QueryClientProvider, and additionally:

useIsRestoring #

If 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.

Persisters #

Persisters Interface #

Persisters have the following interfaces:

1export interface Persister {
2  persistClient(persistClient: PersistedClient): Promisable<void>
3  restoreClient(): Promisable<PersistedClient | undefined>
4  removeClient(): Promisable<void>
5}

Persisted Client entries have the following interface:

1export interface PersistedClient {
2  timestamp: number
3  buster: string
4  cacheState: any
5}

You can import these (to build a persister):

1import {
2  PersistedClient,
3  Persister,
4} from '@tanstack/react-query-persist-client'

Building A Persister #

You can persist however you like. Here is an example of how to build an Indexed DB 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.

 1import { get, set, del } from 'idb-keyval'
 2import {
 3  PersistedClient,
 4  Persister,
 5} from '@tanstack/react-query-persist-client'
 6
 7/**
 8 * Creates an Indexed DB persister
 9 * @see https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API
10 */
11export function createIDBPersister(idbValidKey: IDBValidKey = 'reactQuery') {
12  return {
13    persistClient: async (client: PersistedClient) => {
14      await set(idbValidKey, client)
15    },
16    restoreClient: async () => {
17      return await get<PersistedClient>(idbValidKey)
18    },
19    removeClient: async () => {
20      await del(idbValidKey)
21    },
22  } as Persister
23}