Capítulo 48 de 80

Chapter 48: createSyncStoragePersister

Core Idea

Deprecated — creates a Persister backed by any synchronous Storage-shaped API (window.localStorage/sessionStorage); the docs now recommend createAsyncStoragePersister instead, since it's a strict superset (async storages and sync ones both satisfy its interface).

Key Concepts

  • Package: @tanstack/query-sync-storage-persister (+ @tanstack/react-query-persist-client) — pass the result to persistQueryClient.
  • Retry on write failure: persistence can fail (e.g. localStorage quota exceeded) — a retry function receives { persistedClient, error, errorCount } and returns either a modified PersistedClient to retry with, or undefined to give up. The built-in removeOldestQuery strategy (imported from @tanstack/react-query-persist-client) evicts the oldest query and retries — a common fix for quota errors.
  • Options: storage (required); key (default REACT_QUERY_OFFLINE_CACHE); throttleTime (default 1000ms, batches rapid cache changes into one write); serialize/deserialize (default JSON.stringify/JSON.parse — override with a compressing library like lz-string when localStorage's ~5MB limit is a real constraint).

Code Examples

const localStoragePersister = createSyncStoragePersister({
  storage: window.localStorage,
  retry: removeOldestQuery, // evict oldest query and retry on write failure
})
persistQueryClient({ queryClient, persister: localStoragePersister })
  • What it demonstrates: a sync storage persister with a built-in quota-failure recovery strategy.

Key Takeaways

  1. Prefer createAsyncStoragePersister for new code — this package is deprecated and slated for removal.
  2. Set retry: removeOldestQuery (or a custom strategy) whenever the cache is large enough that localStorage's quota is a realistic concern.
  3. Override serialize/deserialize with a compression library if the persisted cache regularly approaches localStorage's size limit.

Connects To

  • createAsyncStoragePersister: the recommended replacement.
  • persistQueryClient: the orchestrator this persister plugs into.