Persisting the Query Cache with AsyncStorage
Install the React Query persistence plugin, store the entire query cache in AsyncStorage, and restore it on app startup so data is available immediately offline.
Why Persist the Query Cache?
By default the React Query cache exists only in memory. When the app is closed and reopened, all cached data is gone — the user sees loading spinners while data refetches from the network. On slow or absent connections, this means a blank screen.
Cache persistence saves the React Query cache to disk (AsyncStorage on React Native) so data is available immediately on the next app launch, before any network requests complete. This is the foundation of offline-first mobile applications.
Required Packages
Cache persistence requires three packages: @tanstack/react-query (core), @tanstack/react-query-persist-client (the persistence adapter), and a persister implementation. For React Native we use @tanstack/async-storage-persister which wraps AsyncStorage as the persistence backend.
AsyncStorage is the standard key-value store for React Native, provided by @react-native-async-storage/async-storage. The persister serializes the entire query cache to JSON and writes it to a single AsyncStorage key.
// Install all required packages:
// npx expo install @tanstack/react-query
// npx expo install @tanstack/react-query-persist-client
// npx expo install @tanstack/async-storage-persister
// npx expo install @react-native-async-storage/async-storage
import { createAsyncStoragePersister } from '@tanstack/async-storage-persister';
import { PersistQueryClientProvider } from '@tanstack/react-query-persist-client';
import AsyncStorage from '@react-native-async-storage/async-storage';All lessons in this course
- QueryClient, QueryClientProvider, and useQuery
- Mutations with useMutation and Cache Invalidation
- Persisting the Query Cache with AsyncStorage
- Background Refetch and Stale Time Configuration