Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

query-invalidation.md

83 lines2.0 KB

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).