Basic Invalidation
The most common pattern is to invalidate queries in the mutation’sonSuccess or onSettled callback:
invalidateQueries marks queries as stale and triggers a refetch if the query is currently being rendered.onSuccess vs onSettled
onSuccess
Invalidate only when the mutation succeeds:onSettled
Invalidate whether the mutation succeeds or fails:Invalidation Filters
Exact Matching
Invalidate only exact query key matches:Prefix Matching
Invalidate all queries that start with a key prefix:Predicate Filtering
Use custom logic to determine which queries to invalidate:Multiple Query Invalidation
Invalidate multiple related queries:Refetch Options
Control how invalidated queries are refetched:Awaiting Invalidation
Wait for all invalidated queries to refetch:Mutation Context Pattern
Use the context parameter in mutation callbacks:Real-World Example
Complete example with auto-refetching after mutation:Invalidation Without Refetch
Sometimes you want to mark queries as stale without immediately refetching:Query Removal
Remove queries from the cache entirely:removeQueries completely removes the query from cache, while invalidateQueries marks it as stale but keeps the data.Reset Queries
Reset queries to their initial state:Best Practices
1
Use onSettled for optimistic updates
Always invalidate in
onSettled when using optimistic updates to ensure the cache is corrected even if the mutation fails.2
Invalidate broad, refetch narrow
Invalidate all related queries broadly, but only active queries will refetch by default.
3
Leverage query key structure
Design your query keys hierarchically so you can easily invalidate related queries.
4
Consider manual updates
For simple mutations, updating the cache manually might be more efficient than invalidating.