Sub topic 9
Keeping the UI fresh with query invalidation
This chapter assumes you can write a useQuery call, know how query keys identify cache entries, and understand the difference between fresh and stale data. It also assumes you have seen useMutation. Here you connect a mutation to the cache so the screen updates after the server changes.
Why invalidate
After a mutation succeeds, the cached list no longer matches the server. Query invalidation fixes this in two steps:
- It marks every matching query in the cache as stale, regardless of
staleTime. - It refetches the matching queries that are currently being displayed (the active ones).
Inactive queries are only marked stale. They refetch the next time a component uses them.
import { useMutation, useQueryClient } from '@tanstack/react-query'
function AddTodo() {
const queryClient = useQueryClient()
const addTodo = useMutation({
mutationFn: async (title: string) => {
const res = await fetch('/api/todos', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ title }),
})
if (!res.ok) throw new Error(`Request failed: ${res.status}`)
return res.json()
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['todos'] })
},
})
return (
<button
disabled={addTodo.isPending}
onClick={() => addTodo.mutate('Write tutorial')}
>
Add todo
</button>
)
}The list component does not change. It still calls useQuery with queryKey: ['todos'], and it re-renders when the refetch returns.
Key matching is by prefix
invalidateQueries matches keys by prefix. Invalidating ['todos'] also hits ['todos', 5] and ['todos', { status: 'done' }]. This is why a hierarchical key design pays off: one call refreshes the list and every detail entry under it.
| Call | Matches |
|---|---|
| `invalidateQueries({ queryKey: ['todos'] })` | `['todos']`, `['todos', 5]`, `['todos', { page: 2 }]` |
| `invalidateQueries({ queryKey: ['todos', 5] })` | `['todos', 5]` only |
| `invalidateQueries({ queryKey: ['todos'], exact: true })` | `['todos']` only |
| `invalidateQueries()` | Every query in the cache |
Waiting for the refetch
invalidateQueries returns a Promise that resolves when the refetches finish. If you return it from the callback, the mutation stays in the pending state until the list is fresh. That keeps a submit button disabled until the new data is on screen.
onSuccess: () => {
return queryClient.invalidateQueries({ queryKey: ['todos'] })
},Common errors
- Key mismatch. Invalidating
['todo']when the query uses['todos']does nothing and raises no error. Define keys in one shared place. - Invalidating too broadly. Calling
invalidateQueries()with no filter refetches everything on screen. Prefer the narrowest key that covers the change. - Using
onSuccessofuseQuery. Invalidation belongs in the mutation callbacks or in themutatecall. Query-level callbacks no longer exist in v5. - Expecting a refetch for unmounted queries. They are marked stale and refetch later, which is correct behavior.
Exercise
A todo list uses the key ['todos', { status: 'done' }], and a detail view uses ['todos', 7]. A mutation calls invalidateQueries({ queryKey: ['todos'], exact: true }). Which of these queries is invalidated, and how would you change the call to invalidate both?
Show answer
Neither is invalidated, because exact: true only matches a query whose key is exactly ['todos'], and no query here has that key. Remove exact: true so prefix matching applies. Then ['todos'] matches both ['todos', { status: 'done' }] and ['todos', 7].