Open History to see the last commit
1---
2id: query-invalidation
3title: Query Invalidation
4---
5β
6Waiting for queries to become stale is not always enough. After a mutation succeeds, you often know that related cached data is out of date. Use `queryClient.invalidateQueries` to mark matching queries stale and refetch active observers.
7β
8```ts
9queryClient.invalidateQueries()
10β
11queryClient.invalidateQueries({
12 queryKey: ['todos'],
13})
14```
15β
16When a query is invalidated:
17β
18- It is marked stale, overriding any `staleTime`
19- If a matching query is active in a controller, it can refetch in the background
20β
21## Invalidation from Mutations
22β
23```ts
24private readonly addTodo = createMutationController(this, {
25 mutationFn: addTodo,
26 onSuccess: async () => {
27 await queryClient.invalidateQueries({ queryKey: ['todos'] })
28 },
29})
30```
31β
32Use this pattern when the mutation result tells you related cached data is stale. The [Pagination example](../examples/pagination) shows invalidation after project mutations.
33β
34## Query Matching
35β
36Match a group of queries by prefix:
37β
38```ts
39queryClient.invalidateQueries({ queryKey: ['projects'] })
40```
41β
42Both of these query keys match:
43β
44```ts
45const projectsListKey = ['projects']
46const projectsPageKey = ['projects', 1, 250, false]
47```
48β
49Use a more specific key when only one slice should be invalidated:
50β
51```ts
52queryClient.invalidateQueries({
53 queryKey: ['projects', this.page],
54})
55```
56β
57Use `exact: true` to match only the exact key:
58β
59```ts
60queryClient.invalidateQueries({
61 queryKey: ['projects'],
62 exact: true,
63})
64```
65β
66## Manual Cache Updates
67β
68Invalidation is usually simpler than normalized cache updates. When you do need immediate UI updates, combine targeted cache writes with invalidation:
69β
70```ts
71queryClient.setQueryData<TodosResponse>(['todos'], (existing) => {
72 if (!existing) return existing
73β
74 return {
75 ...existing,
76 items: [...existing.items, createdTodo],
77 }
78})
79β
80await queryClient.invalidateQueries({ queryKey: ['todos'] })
81```
82β
83For rollback with optimistic updates, see the mutation guide and the [Pagination example](../examples/pagination).