Skip to main content
TanStack Query supports persisting the query cache to external storage, allowing your app to restore cached data across page reloads and sessions.

Installation

Basic Setup

Storage Options

localStorage

sessionStorage

IndexedDB

For larger datasets:

React Native AsyncStorage

Persist Options

maxAge

Cache expiration time:

buster

Version your cache to invalidate old formats:
Increment the buster value when making breaking changes to your data structure to automatically invalidate old cached data.

Custom Persister

Create a custom persister for any storage:

Selective Persistence

Choose which queries to persist:

Exclude Sensitive Data

Only Persist Recent Queries

Data Serialization

Transform data during persist/restore:

Manual Persistence

For more control, use the persistence functions directly:

Persist Mutations

Persist paused mutations (e.g., offline support):

Error Handling

Handle persistence errors:

Storage Quota Management

Handle storage quota exceeded:

Compression

Compress persisted data to save space:

Multi-Tab Synchronization

Sync cache across browser tabs:

Testing with Persistence

Best Practices

  1. Set appropriate maxAge - Don’t persist stale data indefinitely
  2. Use cache busting - Version your cache for breaking changes
  3. Exclude sensitive data - Never persist auth tokens, passwords, etc.
  4. Handle errors gracefully - App should work even if restoration fails
  5. Monitor storage size - Especially important for mobile apps
  6. Compress large datasets - Use compression for better performance

Common Pitfalls

1. Not Setting gcTime

2. Persisting Everything

3. Forgetting Cache Version

Next Steps

  • SSR - Combine persistence with server-side rendering