Query Docs
Guides & Concepts
- Important Defaults
- Queries
- Query Keys
- Query Functions
- Network Mode
- Parallel Queries
- Dependent Queries
- Background Fetching Indicators
- Window Focus Refetching
- Disabling/Pausing Queries
- Query Retries
- Paginated Queries
- Infinite Queries
- Initial Query Data
- Placeholder Query Data
- Prefetching
- Mutations
- Query Invalidation
- Invalidation from Mutations
- Updates from Mutation Responses
- Optimistic Updates
- Query Cancellation
- Scroll Restoration
- Filters
- SSR & Next.js
- Caching
- Default Query Fn
- Suspense
- Custom Logger
- Testing
- Does this replace [Redux, MobX, etc]?
- Migrating to React Query 3
- Migrating to React Query 4
ESLint
AI/LLM: This documentation page is available in plain markdown format at/query/v4/docs/framework/react/guides/invalidations-from-mutations.md
Guides & Concepts
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:
tsx
const mutation = useMutation({ mutationFn: postTodo })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:
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: () => {
queryClient.invalidateQueries({ queryKey: ['todos'] })
queryClient.invalidateQueries({ queryKey: ['reminders'] })
},
})You can wire up your invalidations to happen using any of the callbacks available in the useMutation hook