Cache Fundamentals
Every query result is cached using thequeryKey as a unique identifier. The cache stores both successful data and error states, allowing TanStack Query to provide instant responses to subsequent requests.
Stale Time
ThestaleTime option determines how long cached data is considered “fresh” before it becomes stale. By default, data is immediately stale (staleTime: 0).
Stale data can still be used to render your UI instantly, but TanStack Query will refetch it in the background to ensure freshness.
Dynamic Stale Time
You can computestaleTime dynamically based on the query:
Garbage Collection Time (gcTime)
ThegcTime (formerly cacheTime) determines how long inactive queries remain in memory before being garbage collected. The default is 5 minutes.
1
Query becomes inactive
When all components using a query unmount, the query becomes inactive.
2
Garbage collection timer starts
A timer starts based on the
gcTime value.3
Cache cleanup
After the timer expires, the query data is removed from memory.
Cache Data Access
You can imperatively access cached data usinggetQueryData:
Manual Cache Updates
You can manually update the cache usingsetQueryData: