Blog>
Snippets

Configuring React Query for Offline Persistence

Demonstrate setting up React Query's QueryClient with offline persistence using the createAsyncStoragePersistor from react-query/createAsyncStoragePersistor and persistQueryClient from react-query/persistQueryClient libraries.
import { QueryClient } from 'react-query';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { createAsyncStoragePersistor } from '@tanstack/query-async-storage-persister';
import { persistQueryClient } from '@tanstack/react-query-persist-client';
Imports necessary libraries and modules. This includes React Query's QueryClient, Async Storage for persistent storage, and persistence utilities from React Query.
const queryClient = new QueryClient();
Initializes the React Query client.
const asyncStoragePersistor = createAsyncStoragePersistor({
  storage: AsyncStorage,
});
Creates an AsyncStorage persistor which React Query can use to persist the cache.
persistQueryClient({
  queryClient,
  persistor: asyncStoragePersistor,
});
Configures the query client to use the created AsyncStorage persistor, enabling offline persistence of the query cache.