The Query Cache
TheQueryCache is responsible for storing and managing all query data. From queryCache.ts:92-98:
- Keys are query hashes (derived from query keys)
- Values are
Queryinstances containing state and data
Cache Time vs Stale Time
Two fundamental timing concepts control caching behavior:Stale Time
Stale time determines how long data is considered fresh:- Default:
0(data is immediately stale) - Purpose: Controls when background refetches occur
- Type:
number | 'static'
types.ts:102-111:
Setting
staleTime: 'static' means the data is never considered stale and won’t automatically refetch.GC Time (Garbage Collection Time)
GC time determines how long inactive data stays in the cache:- Default:
5 minutes(300,000 ms) - Purpose: Controls when unused data is garbage collected
- Renamed from:
cacheTimein v4
types.ts:242-246:
The Relationship
0s- Query executes, data is fresh1m- Data becomes stale (will refetch on next mount/focus)5m- If no observers, data is garbage collected
Stale-While-Revalidate Strategy
TanStack Query implements a stale-while-revalidate pattern:- Serve stale data immediately from cache
- Revalidate in the background if data is stale
- Update UI when fresh data arrives
- No cached data → shows loading state
- Fetches data → shows posts
- Shows cached posts immediately (stale time not exceeded)
- No background fetch
- Shows cached posts immediately
- Fetches in background (
isFetching: true) - Updates when new data arrives
Cache Lifecycle
1. Query Creation
When a query is first used, it’s built in the cache. FromqueryCache.ts:100-131:
2. Observer Subscription
When components use the query, observers are added. Fromquery.ts:343-351:
3. Observer Removal
When components unmount, observers are removed. Fromquery.ts:354-374:
4. Garbage Collection
When a query has no observers, it’s scheduled for garbage collection based ongcTime.
From the Removable class (parent of Query):
Cache Manipulation
Reading Cache Data
Get data from the cache imperatively:queryClient.ts:129-138:
Setting Cache Data
Manually update cache data:queryClient.ts:176-209:
Removing Cache Data
Remove queries from the cache:queryClient.ts:247-256:
Cache Persistence
Persist cache to storage for offline support:examples/react/basic/src/index.tsx:8-18):
Structural Sharing
TanStack Query performs structural sharing to preserve referential equality:types.ts:261-267:
Cache Configuration
Global Defaults
Per-Query Configuration
Query-Specific Defaults
Set defaults for specific query keys:Cache Events
Listen to cache events:queryCache.ts:19-30: