Skip to main content
Query invalidation is the process of marking queries as stale to trigger refetches. It’s essential for keeping your UI in sync with server state after mutations.

What is Invalidation?

When you invalidate a query:
  1. The query is marked as stale (regardless of its staleTime)
  2. If the query is currently being rendered, it refetches in the background
From query.ts:380-384:
And the invalidation is handled in the reducer at query.ts:665-669:

Basic Invalidation

Invalidate Specific Queries

Invalidate Multiple Queries

Invalidation API

From queryClient.ts:293-313, the invalidateQueries method:

Refetch Type

Control which queries are refetched after invalidation:
Active queries are queries currently being observed (rendered in components). Inactive queries are in the cache but not currently observed.

Query Filters

Exact Matching

Prefix Matching (Default)

Predicate Function

Filter by Status

Common Invalidation Patterns

After Mutations

The most common use case - invalidate after creating, updating, or deleting data:

Hierarchical Invalidation

Invalidation vs. Refetch

invalidateQueries

Marks queries as stale and refetches active queries by default:
  • Marks queries as stale immediately
  • Refetches active queries automatically
  • Inactive queries refetch when they become active

refetchQueries

Forces an immediate refetch without marking as stale:
From queryClient.ts:315-339:
Use invalidateQueries for most cases. Use refetchQueries when you need to force an immediate refetch regardless of staleness.

Reset Queries

Reset queries to their initial state:
From queryClient.ts:258-276:
This:
  1. Resets the query state to initial
  2. Refetches active queries

Automatic Invalidation

Window Focus

Queries automatically refetch when the window regains focus (if stale):

Network Reconnection

Queries refetch when the network reconnects (if stale):

Mount

Queries refetch when new instances mount (if stale):

Manual Invalidation Strategy

Conservative Approach

Invalidate only what changed:

Aggressive Approach

Invalidate everything related:

Hybrid Approach

Optimistic update + invalidation:

Cancelling Queries

Cancel in-flight queries before invalidating:
This is useful for optimistic updates to prevent race conditions.

Invalidation Options

Best Practices

1. Use Query Key Factories

2. Invalidate in onSettled

Use onSettled to invalidate whether the mutation succeeds or fails:

3. Be Specific When Possible

4. Combine with Optimistic Updates

Always await cancelQueries before performing optimistic updates to prevent race conditions between your optimistic update and in-flight requests.