Skip to main content
When you mutate data on the server, you need to update your client-side cache to reflect those changes. TanStack Query provides powerful tools for query invalidation that automatically refetch affected queries.

Basic Invalidation

The most common pattern is to invalidate queries in the mutation’s onSuccess 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:
Use onSettled when you want to always refetch, even after errors. This is useful with optimistic updates to ensure the cache is correct.

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:
Refetching all queries (including inactive ones) can be expensive. Use refetchType: 'active' unless you have a specific reason.

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.