Files
upstream-tanstack-query/docs/framework/react/guides/invalidations-from-mutations.md
upstream-mirror 3a013ccdfe
Some checks failed
autofix.ci / autofix (push) Failing after 4s
Release / Release (push) Has been skipped
GitHub Actions Security Analysis / Run zizmor (push) Failing after 2s
snapshot of https://github.com/TanStack/query.git (main, 2026-09-16; blobs > 131072B omitted)
2026-09-16 01:13:08 +05:00

58 lines
2.0 KiB
Markdown

---
id: invalidations-from-mutations
title: Invalidations from Mutations
---
Invalidating queries is only half the battle. Knowing **when** to invalidate them is the other half. Usually when a mutation in your app succeeds, it's VERY likely that there are related queries in your application that need to be invalidated and possibly refetched to account for the new changes from your mutation.
For example, assume we have a mutation to post a new todo:
[//]: # 'Example'
```tsx
const mutation = useMutation({ mutationFn: postTodo })
```
[//]: # 'Example'
When a successful `postTodo` mutation happens, we likely want all `todos` queries to get invalidated and possibly refetched to show the new todo item. To do this, you can use `useMutation`'s `onSuccess` options and the `client`'s `invalidateQueries` function:
[//]: # 'Example2'
```tsx
import { useMutation, useQueryClient } from '@tanstack/react-query'
const queryClient = useQueryClient()
// When this mutation succeeds, invalidate any queries with the `todos` or `reminders` query key
const mutation = useMutation({
mutationFn: addTodo,
onSuccess: async () => {
// If you're invalidating a single query
await queryClient.invalidateQueries({ queryKey: ['todos'] })
// If you're invalidating multiple queries
await Promise.all([
queryClient.invalidateQueries({ queryKey: ['todos'] }),
queryClient.invalidateQueries({ queryKey: ['reminders'] }),
])
},
})
```
[//]: # 'Example2'
Returning a Promise on `onSuccess` makes sure the data is updated before the mutation is entirely complete (i.e., isPending is true until onSuccess is fulfilled)
[//]: # 'Example2'
You can wire up your invalidations to happen using any of the callbacks available in the [`useMutation` hook](./mutations.md)
[//]: # 'Materials'
## Further reading
For a technique to automatically invalidate Queries after Mutations, have a look at [TkDodo's article on Automatic Query Invalidation after Mutations](https://tkdodo.eu/blog/automatic-query-invalidation-after-mutations).
[//]: # 'Materials'