Cache invalidation and stale data

Cache invalidation and stale data

When data looks stale after a mutation, check three layers in order.

  1. React Query cache. invalidateQueries marks a query stale and refetches it lazily, on the next mount. ensureQueryData returns stale cache at once. When the next step needs fresh data (before a navigation whose target loader calls ensureQueryData), use refetchQueries, which fetches now.
  2. TanStack Router context. beforeLoad runs once per mount, and a navigation between siblings (/dashboard/A to /dashboard/B) does not run it again, so route context stays stale after a mutation. Never read reactive data from route context: use useQuery(bootstrapQueryOptions) in the layout, so reactivity comes from the Query cache.
  3. Server TTLCache. invalidateQueries does nothing to a server-side cache. The mutation handler calls invalidateBootstrapCache(userId) (or the cache's equivalent) itself.

The full chain, when all three apply:

await invalidateBootstrapCache(userId);                          // server TTLCache
await queryClient.refetchQueries({ queryKey: bootstrapQueryKey() }); // Query, waits for fresh data
await router.invalidate();                                       // re-runs loaders

Do not add router.invalidate() to every mutation. Prefer a reactive useQuery() in the layout; call router.invalidate() only when a loader must run again.

Polling during a transient state

  • Whole page: router.invalidate() from a useEffect with a setInterval while an entity is creating or bootstrapping. It refetches the loader and every active query; it stops when the guard condition turns false. Reference: src/features/billing/hooks/use-billing-poll.ts.
  • One query: refetchInterval: query => query.state.data?.some(r => r.status === 'running') ? 3000 : false on its queryOptions, without invalidating anything else.