Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does the persistQueryClient from react-query work?

I'm using React Query to make my API calls, but when I reload the page, the state is lost. I posted a question on StackOverflow asking if there is a way to persist data in react-query then someone responded saying that there is a way to do with persistQueryClient, but I tried reading the documentation and I still don't understand how it works. Can someone please explain to me?

https://tanstack.com/query/v4/docs/react/plugins/persistQueryClient

like image 552
Bruno Bispo Avatar asked Jul 16 '26 23:07

Bruno Bispo


1 Answers

The persistQueryClient is a wrapper around the standard queryClient that persists the cache to some form of storage e.g localStorage.

To define and use a persistQueryClient, we'll need to:

  1. Create a query client with a large cache time.
  2. Create a persister
  3. Wrap both the query client and persister in a persistQueryClient.

An example provided by the docs:

import { PersistQueryClientProvider } from '@tanstack/react-query-persist-client'
import { createSyncStoragePersister } from '@tanstack/query-sync-storage-persister'

// 1. the query client
const queryClient = new QueryClient({
  defaultOptions: {
    queries: {
      cacheTime: 1000 * 60 * 60 * 24, // 24 hours
    },
  },
})

// 2. the persister
const persister = createSyncStoragePersister({
  storage: window.localStorage,
})

// 3. Replace the <QueryClientProvider> with <PersistQueryClientProvider>
ReactDOM.createRoot(rootElement).render(
  <PersistQueryClientProvider
    client={queryClient}
    persistOptions={{ persister }}
  >
    <App />
  </PersistQueryClientProvider>
)
like image 151
gnerkus Avatar answered Jul 18 '26 12:07

gnerkus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!