Course contentsShow
← React
Lesson 1783 of 2,39642. Data Fetching LibrariesFree lesson

The cacheTime Configuration

Understanding how long inactive queries remain in memory before garbage collection occurs.

The cacheTime Configuration

You'll learn: How long TanStack Query keeps inactive query data in memory before automatically cleaning it up.

What is cacheTime?

You already know that staleTime controls when data is considered outdated and needs refetching. But cacheTime (also called gcTime in newer versions) answers a different question: How long should we keep cached data in memory after nobody's using it anymore?

Think of it like leftovers in your fridge. Just because you finished dinner (unmounted a component) doesn't mean you throw the food away immediately. You keep it for a while in case you want it again soon. But eventually, if no one touches it, you clean it out.

How It Works

When all components using a particular query unmount (the query becomes "inactive"), TanStack Query starts a countdown based on cacheTime. If no component re-subscribes to that query before the timer runs out, the data gets garbage collected—removed from memory entirely.

Default behavior: cacheTime defaults to 5 minutes (300,000 milliseconds).

const { data } = useQuery({
  queryKey: ['user', userId],
  queryFn: fetchUser,
  cacheTime: 10 * 60 * 1000 // Keep inactive data for 10 minutes
})

Why This Matters

  • Memory management: Prevents your app from accumulating endless cached data
  • Quick returns: If a user navigates back within cacheTime, the data is instantly available (even if stale)
  • Balance: Longer cacheTime = better UX for frequent navigation, but more memory usage

Key Takeaway: cacheTime controls how long inactive queries stay in memory after components unmount—it's your garbage collection window, defaulting to 5 minutes.