Timeline of React Query cache states from fresh to stale, inactive and removed

React Query caching decides when your app shows stored data, when it asks the server again and when it forgets data entirely. Two settings control most of that behavior: staleTime and gcTime. Once their roles are clear, unexpected refetches and outdated screens become easy to explain and fix.

This article follows a query through its full lifecycle, explains each default, lists the events that trigger refetching and shows how invalidation fits in. The examples use TanStack Query v5 names.

The Query Lifecycle

Every query key moves through a predictable sequence. A successful fetch stores data as fresh. After staleTime passes, the data becomes stale but stays visible. When no component observes the key, it becomes inactive, and after gcTime it is removed from memory.

StateWhat it meansWhat happens next
FreshWithin staleTimeServed from cache with no refetch
StalestaleTime has passedRefetched on the next trigger
FetchingA request is runningStatus flags update observers
InactiveNo observers remaingcTime countdown starts
RemovedgcTime endedNext use starts from pending

Understanding staleTime

The staleTime option sets how long data is considered fresh. Its default is zero, meaning data is stale immediately after it arrives. Stale data is still shown to users; the label only means React Query will refetch it in the background when a trigger occurs.

queryClient.js
useQuery({
  queryKey: ['countries'],
  queryFn: fetchCountries,
  staleTime: 10 * 60 * 1000, // ten minutes
});

Picking a Sensible Value

Match staleTime to how often the data really changes. A list of countries can stay fresh for a long time, while stock levels might need a few seconds. Setting staleTime to Infinity keeps data fresh until you invalidate it manually.

Understanding gcTime

The gcTime option controls how long inactive data stays in memory. The default is five minutes. If a user returns to a screen within that window, cached data appears instantly while a background refetch runs. After gcTime, the entry is garbage collected.

How the Two Settings Interact

The settings measure different things and run separately. staleTime counts from the last successful fetch, while gcTime counts from the moment the last observer unmounts. Data can be stale yet cached, or fresh yet inactive.

What Triggers a Refetch

Stale queries refetch in the background when certain events happen. Each trigger has its own option, so you can switch off the ones that do not suit a resource.

  • A new component mounts that observes the key, controlled by refetchOnMount.
  • The browser window regains focus, controlled by refetchOnWindowFocus.
  • The network reconnects, controlled by refetchOnReconnect.
  • A refetchInterval elapses, if one is configured.
  • The key is invalidated through the QueryClient.
queryClient.js
const queryClient = new QueryClient({
  defaultOptions: {
    queries: { staleTime: 60_000, refetchOnWindowFocus: false },
  },
});

Deduplication and Structural Sharing

When several components request the same key at once, only one network request runs and all observers share its result. After a refetch, structural sharing keeps unchanged parts of the data referentially identical, which prevents needless re-renders of components that read those parts.

Invalidation After Changes

Time-based freshness cannot know when your own app changes data. After a mutation, call invalidateQueries with a key prefix. Matching entries become stale immediately, and the ones currently on screen refetch right away.

useUpdateUser.js
useMutation({
  mutationFn: updateUser,
  onSuccess: (_, variables) => {
    queryClient.invalidateQueries({ queryKey: ['users'] });
    queryClient.invalidateQueries({ queryKey: ['users', variables.id] });
  },
});

Writing Directly to the Cache

When the mutation response already contains the updated record, setQueryData writes it into the cache without another request. Combine both techniques: write what you know and invalidate lists that might reorder.

Clearing and Removing Data

Signing out should remove user-specific data. Calling queryClient.clear() empties every query and mutation cache, while removeQueries targets selected keys. Both prevent the next user on a shared device from seeing old information.

Debugging Caching Behavior

The React Query DevTools show each key moving between fresh, stale and inactive, along with observer counts. If a request repeats unexpectedly, check for keys that differ only in type, such as numbers versus strings.

Quick Reference of Defaults

OptionDefault
staleTime0
gcTime5 minutes
retry3 on the client
refetchOnWindowFocustrue
refetchOnReconnecttrue
refetchOnMounttrue

Choosing Settings Per Resource

A single global staleTime rarely suits every endpoint. Set a reasonable default in the QueryClient, then override it on queries that differ. Configuration data, such as feature flags or country lists, can stay fresh for a long time, while dashboards may need short values or polling.

Resource typeSuggested staleTimeReason
Reference listsLong or InfinityRarely changes
User profileA few minutesChanges mainly through your own app
DashboardsSeconds, or an intervalOthers update the data
Search resultsShortDepends on fresh input

Placeholder and Initial Data

The initialData option seeds the cache with real data, for example from a list already loaded, and that data respects staleTime like a normal fetch. The placeholderData option shows temporary values that are never written to the cache, which suits skeleton previews and paginated transitions.

Prefetching Before Navigation

Calling prefetchQuery when a user hovers over a link loads the next screen's data early. If the data is still fresh when the screen mounts, it renders immediately without a loading state, which makes navigation feel instant on slower connections.

Persisting the Cache

The in-memory cache disappears when the page reloads. Optional persister packages save selected queries to localStorage, IndexedDB or AsyncStorage and restore them on startup, so returning users see recent data immediately while fresh requests run in the background.

Persisted data should have a maximum age and must never include sensitive information. Use a buster string tied to your app version so a deployment with changed data shapes discards old cache entries instead of rendering incompatible data.

Server Rendering and Hydration

Frameworks such as Next.js can prefetch queries on the server and send the cache to the browser with the page. Hydration places that data into the client cache, and staleTime then decides whether the browser refetches it immediately after loading.

Conclusion

React Query caching rests on a simple model: staleTime decides when data needs refreshing, gcTime decides when unused data is forgotten, and invalidation handles changes your app makes itself.

Set defaults once in the QueryClient, tune staleTime per resource, and verify the results in the DevTools. The paginated example and the v5 changes show these settings in real code.