File: persistQueryClient.md | Updated: 11/15/2025
Search...
+ K
Auto
Docs Examples GitHub Contributors
Docs Examples GitHub Contributors
Docs Examples GitHub Contributors
Docs Examples Github Contributors
Docs Examples Github Contributors
Docs Examples Github Contributors
Docs Examples Github Contributors
Docs Examples Github Contributors
Maintainers Partners Support Learn StatsBETA Discord Merch Blog GitHub Ethos Brand Guide
Documentation
Framework
React
Version
Latest
Search...
+ K
Menu
Getting Started
Guides & Concepts
API Reference
ESLint
Examples
Plugins
Framework
React
Version
Latest
Menu
Getting Started
Guides & Concepts
API Reference
ESLint
Examples
Plugins
On this page
Copy Markdown
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
----------------
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 , although it is possible to work around this limit using timeoutManager.setTimeoutProvider .
tsx
const queryClient = new QueryClient({
defaultOptions: {
queries: {
gcTime: 1000 * 60 * 60 * 24, // 24 hours
},
},
})
const queryClient = new QueryClient({
defaultOptions: {
queries: {
gcTime: 1000 * 60 * 60 * 24, // 24 hours
},
},
})
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:
tsx
persistQueryClient({ queryClient, persister, buster: buildHash })
persistQueryClientSave({ queryClient, persister, buster: buildHash })
persistQueryClientRestore({ queryClient, persister, buster: buildHash })
persistQueryClient({ queryClient, persister, buster: buildHash })
persistQueryClientSave({ queryClient, persister, buster: buildHash })
persistQueryClientRestore({ queryClient, persister, buster: buildHash })
If data is found to be any of the following:
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.
tsx
persistQueryClientSave({
queryClient,
persister,
buster = '',
dehydrateOptions = undefined,
})
persistQueryClientSave({
queryClient,
persister,
buster = '',
dehydrateOptions = undefined,
})
### 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".
tsx
persistQueryClientSubscribe({
queryClient,
persister,
buster = '',
dehydrateOptions = undefined,
})
persistQueryClientSubscribe({
queryClient,
persister,
buster = '',
dehydrateOptions = undefined,
})
You can use this to restore the cache at moment(s) you choose.
tsx
persistQueryClientRestore({
queryClient,
persister,
maxAge = 1000 * 60 * 60 * 24, // 24 hours
buster = '',
hydrateOptions = undefined,
})
persistQueryClientRestore({
queryClient,
persister,
maxAge = 1000 * 60 * 60 * 24, // 24 hours
buster = '',
hydrateOptions = undefined,
})
Takes the following actions:
This functionality is preserved from version 3.x.
tsx
persistQueryClient({
queryClient,
persister,
maxAge = 1000 * 60 * 60 * 24, // 24 hours
buster = '',
hydrateOptions = undefined,
dehydrateOptions = undefined,
})
persistQueryClient({
queryClient,
persister,
maxAge = 1000 * 60 * 60 * 24, // 24 hours
buster = '',
hydrateOptions = undefined,
dehydrateOptions = undefined,
})
All options available are as follows:
tsx
interface PersistQueryClientOptions {
/** The QueryClient to persist */
queryClient: QueryClient
/** The Persister interface for storing and restoring the cache
* to/from a persisted location */
persister: Persister
/** The max-allowed age of the cache in milliseconds.
* If a persisted cache is found that is older than this
* time, it will be **silently** discarded
* (defaults to 24 hours) */
maxAge?: number
/** A unique string that can be used to forcefully
* invalidate existing caches if they do not share the same buster string */
buster?: string
/** The options passed to the hydrate function
* Not used on `persistQueryClientSave` or `persistQueryClientSubscribe` */
hydrateOptions?: HydrateOptions
/** The options passed to the dehydrate function
* Not used on `persistQueryClientRestore` */
dehydrateOptions?: DehydrateOptions
}
interface PersistQueryClientOptions {
/** The QueryClient to persist */
queryClient: QueryClient
/** The Persister interface for storing and restoring the cache
* to/from a persisted location */
persister: Persister
/** The max-allowed age of the cache in milliseconds.
* If a persisted cache is found that is older than this
* time, it will be **silently** discarded
* (defaults to 24 hours) */
maxAge?: number
/** A unique string that can be used to forcefully
* invalidate existing caches if they do not share the same buster string */
buster?: string
/** The options passed to the hydrate function
* Not used on `persistQueryClientSave` or `persistQueryClientSubscribe` */
hydrateOptions?: HydrateOptions
/** The options passed to the dehydrate function
* Not used on `persistQueryClientRestore` */
dehydrateOptions?: DehydrateOptions
}
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:
tsx
// π¨ never unsubscribes from syncing
persistQueryClient({
queryClient,
persister: localStoragePersister,
})
// π¨ happens at the same time as restoring
ReactDOM.createRoot(rootElement).render(<App />)
// π¨ never unsubscribes from syncing
persistQueryClient({
queryClient,
persister: localStoragePersister,
})
// π¨ happens at the same time as restoring
ReactDOM.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 :
tsx
import { PersistQueryClientProvider } from '@tanstack/react-query-persist-client'
import { createAsyncStoragePersister } from '@tanstack/query-async-storage-persister'
const queryClient = new QueryClient({
defaultOptions: {
queries: {
gcTime: 1000 * 60 * 60 * 24, // 24 hours
},
},
})
const persister = createAsyncStoragePersister({
storage: window.localStorage,
})
ReactDOM.createRoot(rootElement).render(
<PersistQueryClientProvider
client={queryClient}
persistOptions={{ persister }}
>
<App />
</PersistQueryClientProvider>,
)
import { PersistQueryClientProvider } from '@tanstack/react-query-persist-client'
import { createAsyncStoragePersister } from '@tanstack/query-async-storage-persister'
const queryClient = new QueryClient({
defaultOptions: {
queries: {
gcTime: 1000 * 60 * 60 * 24, // 24 hours
},
},
})
const persister = createAsyncStoragePersister({
storage: window.localStorage,
})
ReactDOM.createRoot(rootElement).render(
<PersistQueryClientProvider
client={queryClient}
persistOptions={{ persister }}
>
<App />
</PersistQueryClientProvider>,
)
PersistQueryClientProvider takes the same props as QueryClientProvider , and additionally:
optional
will be called when the initial restore is finished
can be used to resumePausedMutations
if a Promise is returned, it will be awaited; restoring is seen as ongoing until then
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:
tsx
export interface Persister {
persistClient(persistClient: PersistedClient): Promisable<void>
restoreClient(): Promisable<PersistedClient | undefined>
removeClient(): Promisable<void>
}
export interface Persister {
persistClient(persistClient: PersistedClient): Promisable<void>
restoreClient(): Promisable<PersistedClient | undefined>
removeClient(): Promisable<void>
}
Persisted Client entries have the following interface:
tsx
export interface PersistedClient {
timestamp: number
buster: string
clientState: DehydratedState
}
export interface PersistedClient {
timestamp: number
buster: string
clientState: DehydratedState
}
You can import these (to build a persister):
tsx
import {
PersistedClient,
Persister,
} from '@tanstack/react-query-persist-client'
import {
PersistedClient,
Persister,
} from '@tanstack/react-query-persist-client'
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.
tsx
import { get, set, del } from 'idb-keyval'
import {
PersistedClient,
Persister,
} from '@tanstack/react-query-persist-client'
/**
* Creates an Indexed DB persister
* @see https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API
*/
export function createIDBPersister(idbValidKey: IDBValidKey = 'reactQuery') {
return {
persistClient: async (client: PersistedClient) => {
await set(idbValidKey, client)
},
restoreClient: async () => {
return await get<PersistedClient>(idbValidKey)
},
removeClient: async () => {
await del(idbValidKey)
},
} satisfies Persister
}
import { get, set, del } from 'idb-keyval'
import {
PersistedClient,
Persister,
} from '@tanstack/react-query-persist-client'
/**
* Creates an Indexed DB persister
* @see https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API
*/
export function createIDBPersister(idbValidKey: IDBValidKey = 'reactQuery') {
return {
persistClient: async (client: PersistedClient) => {
await set(idbValidKey, client)
},
restoreClient: async () => {
return await get<PersistedClient>(idbValidKey)
},
removeClient: async () => {
await del(idbValidKey)
},
} satisfies Persister
}
[###### Want to Skip the Docs?
Query.gg - The Official React Query Course
\
βIf youβre serious about *really* understanding React Query, thereβs no better way than with query.ggββTanner Linsley
Learn More](https://query.gg/?s=tanstack)
