Cache Garbage Collection: cacheTime / gcTime
You'll learn how TanStack Query decides when to throw away cached data that no one is using anymore.
The Cache Cleanup Problem
You've seen how staleTime determines when data is considered outdated. But what about data that's no longer being observed by any component? If you navigate away from a page, should that cached query data sit in memory forever?
This is where cache garbage collection comes in.
cacheTime (or gcTime in v5+)
When a query has zero active observers (no component is currently using it), TanStack Query starts a timer. After cacheTime milliseconds pass, that cached data is completely removed from memory.
Note: In TanStack Query v5+, this option was renamed to gcTime (garbage collection time), but the concept is identical.
useQuery({
queryKey: ['user', userId],
queryFn: fetchUser,
cacheTime: 5 * 60 * 1000 // 5 minutes (v4)
// gcTime: 5 * 60 * 1000 // same thing in v5
})
How It Works
- User visits a page → query becomes active (has observers)
- User navigates away → query becomes inactive (zero observers)
- Garbage collection timer starts (default: 5 minutes)
- If user returns before timer expires → instant cache hit!
- If timer expires first → cache deleted, fresh fetch on next mount
The Analogy
Think of cacheTime like a library's "hold shelf." When you return a book, they keep it on the hold shelf for a few days in case you want to check it out again. After that grace period? Back to the stacks.
Key Takeaway: cacheTime / gcTime controls how long inactive cached data stays in memory before being garbage collected—balancing memory usage with the convenience of instant cache hits when revisiting components.