Cache invalidation and stale data
Cache invalidation and stale data
When data looks stale after a mutation, check three layers in order.
- React Query cache.
invalidateQueriesmarks a query stale and refetches it lazily, on the next mount.ensureQueryDatareturns stale cache at once. When the next step needs fresh data (before a navigation whose target loader callsensureQueryData), userefetchQueries, which fetches now. - TanStack Router context.
beforeLoadruns once per mount, and a navigation between siblings (/dashboard/Ato/dashboard/B) does not run it again, so route context stays stale after a mutation. Never read reactive data from route context: useuseQuery(bootstrapQueryOptions)in the layout, so reactivity comes from the Query cache. - Server TTLCache.
invalidateQueriesdoes nothing to a server-side cache. The mutation handler callsinvalidateBootstrapCache(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 auseEffectwith asetIntervalwhile an entity iscreatingorbootstrapping. 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 : falseon itsqueryOptions, without invalidating anything else.