Email copiado — support@tuurt.com
Cargando experiencia
react · October 30, 2026 · 8 min

TanStack Query and Shared Cache: When to Invalidate and When to Let It Refetch on Its Own

Two screens sharing the same query key can end up fighting over data freshness. We go through invalidateQueries, staleTime, and gcTime, and the real bugs that show up when they get mixed up without noticing.

By Tuurt Team

TanStack Query and Shared Cache: When to Invalidate and When to Let It Refetch on Its Own

Two screens that read the same resource and declare it under the same query key feel like a design win: a single source of truth, no duplicated fetch logic, no manual syncing between two copies of the same data. And it usually is a win. The problem shows up when those two screens don't expect the same freshness from that data, and nobody noticed until a user reported that the list was showing stale state right after saving a change from the edit form.

One key, one cache entry

TanStack Query doesn't keep a separate copy of the data for every useQuery that requests it. It keeps a single entry per query key inside the QueryClient, and every useQuery using that key is an observer of that same entry. That's the whole reason sharing keys works so well to avoid duplicate fetches, and it's also the reason freshness bugs show up: whatever one observer does to the cache affects every other observer on that same key, even if they live in completely different parts of the component tree.

// List screen
useQuery({
  queryKey: ['order', id],
  queryFn: () => fetchOrderSummary(id),
  staleTime: 5 * 60 * 1000, // the summary rarely changes, no need to refetch often
})

// Edit screen, same resource
useQuery({
  queryKey: ['order', id],
  queryFn: () => fetchOrderFull(id),
  staleTime: 0, // before editing, we want the freshest data available
})

This is already a bug waiting to happen, even if it's not obvious right away: the two screens declare different queryFn implementations for the same key. TanStack Query doesn't check that every observer on a key uses the same fetch function; it uses whichever observer happened to trigger the fetch at that moment, and the result gets written under that key with no record of where it came from. If fetchOrderSummary returns an object with fewer fields than fetchOrderFull, the edit screen can end up rendering an incomplete object if the summary fetch was the last one to write the cache.

The root cause isn't different staleTime values between screens — that's actually supported, each observer is allowed to ask for its own freshness. The root cause is sharing a key between two fetchers that return different data shapes. The fix isn't to sync up the staleTime values, it's to split the keys: ['order', id, 'summary'] and ['order', id, 'full'], each with its own data contract, and use invalidateQueries({ queryKey: ['order', id] }) — without the third segment — whenever something changes and both need refreshing, since TanStack Query matches by key prefix by default.

invalidateQueries doesn't refetch what's asleep

The most common bug we see in production code is assuming invalidateQueries forces an immediate refetch everywhere. It doesn't. invalidateQueries marks the entry as stale and triggers an immediate refetch only for active observers — components currently mounted. For queries with no active observers, the data simply gets flagged as old, and the actual refetch only happens once a component mounts a useQuery with that key again.

const mutation = useMutation({
  mutationFn: updateOrder,
  onSuccess: (_, variables) => {
    queryClient.invalidateQueries({ queryKey: ['order', variables.id] })
  },
})

If the user edits the order from a detail screen and then goes back to the list, and the list was unmounted while editing, the list doesn't refetch at the moment of the mutation — there was no active observer. It refetches once the list mounts its useQuery again, provided refetchOnMount isn't set to false. If someone set refetchOnMount: false on the list to cut down on network calls, the effect is that the list keeps showing stale data indefinitely, even after an explicit invalidation, because invalidating only flags the data as old — it won't fetch it unless something is observing it and allowed to refetch on mount.

The practical rule we apply: refetchOnMount: false is safe on screens where the user can tolerate slightly stale data and where some other signal is going to bring in the fresh data anyway — a manual refetch, a WebSocket event. On any screen that depends on invalidations triggered by mutations happening on a different screen, we leave refetchOnMount at its default.

gcTime is not staleTime, and mixing them up breaks navigation

staleTime says how long the data is considered fresh — during that window, a new observer won't trigger a fetch. gcTime (called cacheTime in TanStack Query v4) says how long the entry is kept in memory after the last observer unmounts, before the garbage collector removes it entirely. These are independent axes, and confusing them produces a specific bug: the user navigates from screen A to screen B and back to A within a reasonable amount of time, expecting it to feel instant because "it was still fresh," but instead sees a full loading spinner.

This happens when gcTime is shorter than the time the user actually spent away from screen A. By default, gcTime is five minutes. If the user spent fifteen seconds on screen B, A's entry should still be in cache — fifteen seconds is well under five minutes — so going back to A should show the cached data instantly, and only refetch in the background if staleTime has already elapsed. The typical bug that breaks this anyway is a gcTime explicitly configured lower than staleTime on the same query:

useQuery({
  queryKey: ['order', id],
  queryFn: () => fetchOrder(id),
  staleTime: 5 * 60 * 1000,
  gcTime: 30 * 1000, // shorter than staleTime: the entry gets purged before it stops being "fresh"
})

With this combination, the data never actually becomes stale on its own terms — technically it would still be fresh for another four and a half minutes — but the entire cache entry gets removed thirty seconds after it loses its last observer, because gcTime doesn't know or care whether the data was still considered fresh. The next useQuery with that key finds nothing cached, so it starts from isLoading: true, at the same cost as a first-ever fetch. The rule we follow is simple and rarely fails: gcTime should always be greater than or equal to staleTime on the same query. If staleTime is five minutes, gcTime shouldn't drop below that, and we normally leave it at its default unless there's a concrete memory reason to lower it.

When two screens genuinely need to share a key

There are legitimate cases for a single key across two screens — a list and a detail modal that render exactly the same data shape, for instance. There, the pattern we use is declaring staleTime and gcTime once, in a shared function that both useQuery calls import, instead of repeating the numbers in each component:

export const orderQueryOptions = (id: string) => ({
  queryKey: ['order', id] as const,
  queryFn: () => fetchOrder(id),
  staleTime: 60 * 1000,
  gcTime: 5 * 60 * 1000,
})

// From any screen
useQuery(orderQueryOptions(id))

This doesn't stop a single observer from asking for a different staleTime on a case-by-case basis — it's still a per-call option — but it prevents the most common version of this bug: two developers, on two different screens, writing incompatible freshness settings for the same resource without knowing the other screen exists. If the result also needs to be shaped differently per screen, we use the select option to derive the view from the same cache entry instead of declaring a separate key per presentation shape:

const { data: customerName } = useQuery({
  ...orderQueryOptions(id),
  select: (order) => order.customer.name,
})

What didn't work the first time

The first time we debugged one of these cases, the symptom was that the order list kept showing the previous state for several seconds after confirming a payment from the detail screen. We assumed the mutation's onSuccess was missing an invalidateQueries call, and added one. Nothing changed, because the invalidateQueries call was already there, added by another developer in an earlier version of the same flow, and the list was in fact being correctly marked as stale. The actual problem was that the list was unmounted at that moment — the user had navigated to the detail screen from a different route that unmounted the list component entirely — and when it remounted, a refetchOnMount: false added months earlier to "avoid flicker" was blocking the refetch the invalidation had queued up. We found it by opening the React Query Devtools and looking at the real state of each query — stale, fresh, number of active observers — at the exact moment of navigation, instead of assuming the problem was in the mutation.

What we check before sharing a key between screens

Before letting two screens share a query key, we first confirm both expect exactly the same data shape; if not, we split the keys by suffix and use prefix-based invalidation to refresh both at once. We check that no screen has refetchOnMount: false if it depends on invalidations triggered from another screen, because that combination leaves stale data in place indefinitely. And we verify that gcTime is never lower than staleTime on the same query, because that's the quietest way to turn a navigation that should feel instant into a full loading spinner.

react tanstack-query frontend performance
← Back to blog