TL;DR: Cache invalidation is the hardest problem in caching. TanStack Query provides a rich invalidation API:
invalidateQuerieswith query filter matching,refetchQueriesfor immediate refresh,removeQueriesfor garbage collection, andsetQueryDatafor surgical updates. This guide covers six invalidation patterns for common SaaS scenarios.
Introduction
TanStack Query's cache is a key-value store where the key is your query key structure. Invalidation is the process of marking cached data as stale and optionally refetching it. The art is knowing exactly which queries to invalidate when data changes.
Precise Invalidation
const queryClient = useQueryClient()
// Invalidate all product queries
queryClient.invalidateQueries({ queryKey: ['products'] })
// Invalidate a single product
queryClient.invalidateQueries({ queryKey: ['product', productId] })
// Invalidate with filter
queryClient.invalidateQueries({
queryKey: ['products'],
predicate: (query) => query.queryKey.includes('active'),
})
Mutation Response Invalidation
export function useCreateProduct() {
const queryClient = useQueryClient()
return useMutation({
mutationFn: createProductFn,
onSuccess: (newProduct) => {
// Update the single product cache
queryClient.setQueryData(['product', newProduct.id], newProduct)
// Invalidate the list
queryClient.invalidateQueries({ queryKey: ['products'] })
// Invalidate related counts
queryClient.invalidateQueries({ queryKey: ['dashboard', 'stats'] })
},
})
}
Invalidation Strategy Matrix
| Pattern | Method | When to Use | Cost |
|---|---|---|---|
| Full invalidation | invalidateQueries | After create/delete | Medium (refetch) |
| Precise update | setQueryData | After update | Low (no network) |
| Optimistic + rollback | onMutate + onError | Instant UI | Medium |
| Targeted refetch | refetchQueries | Stale data tolerance | Medium |
| Remove + lazy load | removeQueries | User logout | Low |
| Background refetch | refetchInterval | Dashboards | Persistent |
Conclusion
Effective cache management in TanStack Query is about choosing the right invalidation strategy for each mutation type. For list mutations, invalidate. For single item mutations, use setQueryData. For instant UI, use optimistic updates with rollback.
For a practical walkthrough of immediate UI feedback, see TanStack Query: Optimistic Updates. If your app needs to work without a network connection, Offline Support covers persistence patterns. For real-time data synchronization, WebSocket Real-Time Data integrates with server-sent events, and the Edge Caching Strategies Guide covers CDN-level caching that complements TanStack Query's client cache.