Automatic Caching: How TanStack Query Stores Data
You'll learn how TanStack Query automatically stores fetched data in memory and manages its lifecycle behind the scenes.
The In-Memory Cache Explained
When you call useQuery, TanStack Query doesn't just fetch data and forget about it. It stores the result in an in-memory cache using your query key as the identifier. Think of it like a smart filing cabinet: when you request data with a specific key, TanStack Query checks if it already has a fresh copy filed away before making a new network request.
This happens completely automatically—no manual storage code required.
How Queries Are Stored
Each query is stored as a cache entry identified by its query key:
['todos']→ stores the todos array['todo', 5]→ stores the specific todo with ID 5['user', 'profile']→ stores user profile data
When a component unmounts or stops using a query, the cached data doesn't immediately disappear. It enters an inactive state.
Cache Lifetime Behavior
TanStack Query follows a lifecycle for cached data:
- Active: At least one component is using this query
- Inactive: No components currently need it, but it stays in cache
- Garbage collected: After being inactive for
cacheTime(default: 5 minutes), the data is removed
This means if you navigate away from a page and come back within 5 minutes, the data is still there—instant display! The query can still refetch in the background based on staleTime, but users see cached data immediately while waiting.
Key Takeaway: TanStack Query automatically caches all fetched data in memory using query keys as identifiers, keeps inactive data for 5 minutes by default, and serves cached data instantly when components re-mount—no manual cache management needed.