Skip to main content
TanStack Query provides powerful caching mechanisms that automatically manage the lifecycle of your data. Understanding how caching works is essential to building efficient applications.

Cache Fundamentals

Every query result is cached using the queryKey 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

The staleTime 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 compute staleTime dynamically based on the query:

Garbage Collection Time (gcTime)

The gcTime (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 using getQueryData:
getQueryData is non-reactive. Use it for imperative operations like optimistic updates, not for rendering. Use useQuery in components to subscribe to cache changes.

Manual Cache Updates

You can manually update the cache using setQueryData:

Structural Sharing

TanStack Query uses structural sharing by default to minimize re-renders. This means that if the new data is deeply equal to the old data, the old reference is kept.

Cache Persistence

You can persist the cache to local storage or other storage mechanisms:
Combine persistence with a long gcTime to create offline-capable applications that work seamlessly across page reloads.

Cache Strategies

Prefetch Strategy

Prefetch data before it’s needed:

Initial Data Strategy

Seed the cache with initial data:

Placeholder Data Strategy

Show placeholder data while loading: