Set freshness from business change frequency and explain why garbage-collection time does not prevent background refetching.
Freshness and retention are different questions
staleTime controls how long data remains fresh; gcTime controls how long an inactive query without observers remains cached. Cached data is stale by default, while inactive queries are normally collected after five minutes. Increasing gcTime does not make data fresh.
Put time policy in the query contract
queryOptions returns the supplied configuration at runtime while preserving the type relationship between queryKey and queryFn. Loader prefetching, component reads, and cache writes should reuse the contract so one resource does not acquire conflicting time policies.
import { queryOptions } from '@tanstack/react-query'
export const issueOptions = (issueId: string) => queryOptions({
queryKey: ['issues', 'detail', issueId] as const,
queryFn: () => getIssue(issueId),
staleTime: 60_000,
gcTime: 10 * 60_000,
})Turn this lesson into a verifiable skill
Choose staleTime from business change frequency and distinguish freshness from inactive-cache collection.
Define distinct freshness policies for issue lists, issue details, and a static priority dictionary, then justify them.
Use Devtools to observe fresh, stale, and inactive states and verify focus refetching matches the policy.
- Using gcTime to control whether data refetches.
- Disabling every automatic refetch to hide an incorrect freshness policy.