Cache Staleness: staleTime Explained
What you'll learn: How to control when TanStack Query considers cached data "stale" and decides it needs refetching.
What Is Stale Data?
In TanStack Query, cached data can be in two states: fresh or stale. Fresh data is "good enough" — Query won't refetch it automatically. Stale data is "potentially outdated" — Query will refetch it in the background when certain conditions are met (like component remounting or window refocusing).
By default, data becomes stale immediately after caching (staleTime: 0). This means every time you navigate back to a component, Query refetches in the background.
Configuring staleTime
The staleTime option controls how long (in milliseconds) data stays fresh:
useQuery({
queryKey: ['user', userId],
queryFn: fetchUser,
staleTime: 5 * 60 * 1000 // 5 minutes
})
With staleTime: 5 * 60 * 1000, the data stays fresh for 5 minutes. During that window:
- No background refetches occur
- You see cached data instantly
- No loading states trigger
After 5 minutes, the data becomes stale and Query will refetch on the next trigger (remount, refocus, etc).
Choosing staleTime
Think about your data's nature:
- Fast-changing data (live scores):
staleTime: 0(default) - Moderate updates (user profile):
staleTime: 1-5 minutes - Rarely changes (configuration):
staleTime: Infinity(never stale)
The analogy: staleTime is like the "best by" date on food. Before that time, you trust it without checking. After, you might want to verify it's still good.
Key Takeaway: staleTime determines how long TanStack Query trusts cached data before marking it for potential refetch — balancing freshness needs against unnecessary network requests.