Basic Mutation
Use theuseMutation hook to perform mutations:
Mutation Results
The mutation result contains state and functions:Mutation vs MutateAsync
- mutate
- mutateAsync
Mutation Side Effects
Execute callbacks at different stages of the mutation:Invalidating Queries
Invalidate and refetch queries after mutations:invalidateQueries marks queries as stale and triggers a refetch if they are currently being rendered.Optimistic Updates
Update the UI before the mutation completes:1
Cancel Queries
Cancel any outgoing refetches to prevent them from overwriting optimistic updates.
2
Snapshot
Save the current query data to enable rollback on error.
3
Update
Optimistically update the cache with the expected result.
4
Error Handling
Rollback to the snapshot if the mutation fails.
5
Refetch
Always refetch to ensure data consistency.
Optimistic UI Updates
Show optimistic state in the UI without updating the cache:Mutation Updates from Responses
Update the cache with the mutation response:Sequential Mutations
Execute mutations one after another:Mutation Retry
Mutations do not retry by default, but you can enable it:Mutation Scopes
Control when mutations can run with mutation scope:Persisting Mutations
Mutations can be persisted to storage and resumed:Global Mutation Callbacks
Set up global mutation callbacks in the QueryClient:Mutation Keys
Optionally identify mutations with keys:- Access mutation state with
useMutationState - Filter mutations in global callbacks
- Cancel specific mutations
Accessing Mutation State
Access the state of mutations from anywhere:Error Handling
- Per Mutation
- Global Default
- Inline Callbacks