Sub topic 9
Keeping the UI fresh with query invalidation
This chapter assumes you can write useQuery and useMutation calls, that you know how query keys identify cache entries, and that you understand staleTime and gcTime. If those are unfamiliar, review the earlier chapters on query keys and the cache first.
Why invalidation exists
A mutation changes data on the server. The cache still holds the old copy. Until something tells TanStack Query that the copy is out of date, components keep showing it.
You could patch the cache by hand after every mutation. That works for simple cases, but it forces each mutation to know every query that might show the changed data. Invalidation takes a different approach. You say which cached data is no longer trustworthy, and the library refetches it from the server.
queryClient.invalidateQueries does two things:
- It marks every matching query as stale, whatever its
staleTime. - It refetches the matching queries that are currently active, meaning at least one mounted component is observing them.
Queries that match but are inactive are only marked stale. They refetch the next time a component mounts and uses them.
The basic pattern
The most common use is inside a mutation's onSuccess callback.
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>
)
}After the POST succeeds, the ['todos'] list is marked stale. If the list is on screen, it refetches and the new item appears. You never touched the list component.
How keys are matched
Invalidation matches by key prefix. The key you pass is compared with the start of each cached key, element by element. Objects inside keys are compared by structure, and property order does not matter.
Suppose the cache contains these entries:
| Cached key | Matched by `['todos']`? | Matched by `['todos', 5]`? |
|---|---|---|
| `['todos']` | Yes | No |
| `['todos', 5]` | Yes | Yes |
| `['todos', 7]` | Yes | No |
| `['todos', { filter: 'done' }]` | Yes | No |
| `['projects']` | No | No |
This is why key design matters. If the list key is ['todos'] and each detail key is ['todos', id], one call to invalidateQueries({ queryKey: ['todos'] }) refreshes the list and every cached detail entry.
Narrowing the match
Prefix matching is often broader than you need. Two options narrow it.
exact: truematches only a query whose key equals the one you pass.invalidateQueries({ queryKey: ['todos'], exact: true })refreshes the list and leaves['todos', 5]alone.predicateis a function that receives each query and returns true or false. Use it for rules that a key prefix cannot express.
import { QueryClient } from '@tanstack/react-query'
const queryClient = new QueryClient()
// Only the list, not the detail entries
queryClient.invalidateQueries({ queryKey: ['todos'], exact: true })
// Any todos query whose key includes a filter object with done: true
queryClient.invalidateQueries({
queryKey: ['todos'],
predicate: (query) => {
const part = query.queryKey[1]
return typeof part === 'object' && part !== null && 'done' in part && part.done === true
},
})Calling invalidateQueries() with no arguments invalidates every query in the cache. That is rarely what you want. It is reasonable after something global changes, such as a user logging in as a different account. For logout, queryClient.clear() is usually better, because it removes the cached data instead of keeping it around stale.
Controlling the refetch
invalidateQueries takes a second argument with options. The one you will use most is refetchType.
| `refetchType` | Behavior |
|---|---|
| `'active'` (default) | Refetch matching queries that are being observed. |
| `'inactive'` | Refetch only matching queries with no observers. |
| `'all'` | Refetch every matching query. |
| `'none'` | Mark stale and refetch nothing. |
'none' is useful when you want the data flagged but do not want a network request yet. The next mount or window focus picks it up, subject to the usual refetch rules.
queryClient.invalidateQueries(
{ queryKey: ['todos'] },
{ cancelRefetch: true },
)cancelRefetch defaults to true. If a matching query is already fetching, that request is cancelled and a new one starts. This is the right default after a mutation, because the in-flight response may have been produced before the change. Set it to false if you want to keep the current request.
Waiting for the refetch
invalidateQueries returns a Promise. It resolves when the refetches it started have finished. This matters inside mutation callbacks, because the mutation's isPending state depends on what you return.
const addTodo = useMutation({
mutationFn: createTodo,
onSuccess: () => {
// Returning the promise keeps the mutation pending
// until the list has been refetched.
return queryClient.invalidateQueries({ queryKey: ['todos'] })
},
})If you return the promise, the button stays disabled until the new list has arrived. If you do not return it, the mutation finishes at once and the list updates a moment later. Pick based on the experience you want. Returning it prevents double submits in the gap, and not returning it feels faster.
Invalidation versus setQueryData
When a mutation returns the updated record, you can write it straight into the cache.
const updateTodo = useMutation({
mutationFn: saveTodo,
onSuccess: (updated) => {
queryClient.setQueryData(['todos', updated.id], updated)
queryClient.invalidateQueries({ queryKey: ['todos'], exact: true })
},
})This avoids a request for the detail entry and still refreshes the list. The trade-offs:
- Invalidation is simple and always correct, because the server is the source of truth. It costs a request.
setQueryDatasaves the request and updates instantly. You must make sure the data you write has the same shape that the query function returns, or components will break.- A common mix is to write the response you already have and invalidate the entries whose content you cannot compute locally, such as sorted or filtered lists.
Common errors
- Key mismatch. The mutation invalidates
['todo']but the query uses['todos']. Nothing refreshes and nothing warns you. Define keys in one shared place, for example a small object of key builders, and import them in both spots. - Invalidating before the write finishes. Calling
invalidateQueriesright aftermutate(...), instead of inonSuccessoronSettled, can refetch the old data. - Using
onSuccesswhen you need cleanup on failure.onSuccessruns only when the mutation succeeds. If the server may have applied a change even when the request errors, useonSettled, which runs in both cases. - Expecting inactive queries to refetch. They are only marked stale. If a screen is not mounted, nothing is fetched until it is.
- Over-invalidating. Passing no key refetches every active query and can create a burst of requests. Prefer the narrowest key that covers the change.
- Query functions that do not throw. A refetch that gets a 500 response and returns the error body as data will replace good data with garbage. Always throw on
!res.ok.
Putting it together
Consider a todo app with a list, a detail view, and a form that edits a todo. A reasonable setup:
- The list uses
['todos'], and the detail uses['todos', id]. - The edit mutation writes the returned todo into
['todos', id]withsetQueryData. - In
onSuccess, it invalidates['todos']withexact: true, so the list reorders if the title changed. - It returns the invalidation promise, so the submit button stays disabled until the list is current.
This gives an instant detail view, a correct list, and one background request.
Exercise
A page shows ['todos'] (the list) and ['todos', 3] (a detail view). The detail view is currently unmounted, but its entry is still in the cache. You call queryClient.invalidateQueries({ queryKey: ['todos'] }) after a mutation. Which queries are marked stale, which are refetched immediately, and what happens to the detail entry later?
Show answer
Both ['todos'] and ['todos', 3] match by prefix, so both are marked stale. Only ['todos'] is active, so only it refetches immediately. ['todos', 3] has no observers, so it is not fetched. It refetches the next time a component that uses it mounts. Passing refetchType: 'all' would have refetched it right away.
Exercise
Why might you return the promise from invalidateQueries inside a mutation's onSuccess, and what is the downside?
Show answer
Returning it keeps the mutation in the pending state until the refetch finishes, so a submit button bound to isPending stays disabled until the list is up to date. This prevents duplicate submissions and a flash of old data after the mutation reports success. The downside is that the mutation appears to take longer, because it now includes the refetch time.