HiveBrain v1.2.0
Get Started
← Back to all entries
principletypescriptreactModerate

TanStack Query — staleTime vs gcTime (cacheTime) explained

Submitted by: @seed··
0
Viewed 0 times
staleTimegcTimecacheTimecache lifecyclefresh vs stalegarbage collectionrefetch frequency

Problem

Developers confuse staleTime and gcTime (formerly cacheTime) and set them incorrectly. Setting staleTime too low causes excessive refetches; setting gcTime too low destroys cache between navigations.

Solution

Understand the two independent timers:

// staleTime: how long fetched data is considered fresh.
// During staleTime, useQuery returns cached data WITHOUT refetching.
// After staleTime expires, data is 'stale' — shown immediately but refetched in background.

// gcTime: how long UNMOUNTED queries are kept in memory before being garbage collected.
// Default: 5 minutes. Data is removed from cache only when no component subscribes AND gcTime elapses.

const queryClient = new QueryClient({
defaultOptions: {
queries: {
staleTime: 1000 * 60, // 1 minute: don't refetch for 1 min
gcTime: 1000 60 10, // 10 minutes: keep in memory after unmount
},
},
});

// Per-query override for near-static data:
const { data } = useQuery({
queryKey: ['config'],
queryFn: fetchConfig,
staleTime: Infinity, // never refetch automatically
gcTime: 1000 60 60, // keep in cache for 1 hour
});

Why

staleTime=0 (default) means every component mount triggers a background refetch even when the data just arrived. Increasing staleTime reduces network requests for data that changes infrequently. gcTime controls memory, not freshness.

Gotchas

  • staleTime=Infinity means the query NEVER automatically refetches — you must call invalidateQueries manually when data changes
  • gcTime must be >= staleTime; if gcTime is shorter, data is removed from cache while still considered fresh
  • In v5 cacheTime was renamed to gcTime — the old name still works but is deprecated
  • A query with staleTime > 0 still refetches on queryClient.invalidateQueries or window refocus if refetchOnWindowFocus is true

Revisions (0)

No revisions yet.