Mutation Basics
A mutation is created using theuseMutation hook:
Mutation States
A mutation can be in one of the following states:Status States
idle- The mutation is idle or fresh/resetpending- The mutation is currently runningerror- The mutation encountered an errorsuccess- The mutation was successful
mutation.ts:26-41, the mutation state structure is:
Derived Boolean States
The mutation result includes convenient boolean flags derived frommutationObserver.ts:145-159:
Mutation Functions
mutate
Themutate function is used to trigger the mutation. It’s fire-and-forget - errors are not thrown but passed to callbacks:
mutateAsync
ThemutateAsync function returns a Promise, allowing you to use async/await:
Side Effects
Mutations support several lifecycle callbacks for performing side effects:onMutate
Called before the mutation function is fired. Useful for optimistic updates:onSuccess
Called when the mutation succeeds:onError
Called when the mutation encounters an error:onSettled
Called when the mutation finishes, regardless of success or failure:Callback Execution Order
Callbacks are executed in the following order, as implemented inmutationObserver.ts:161-219:
onMutate(before the mutation function)- Mutation function executes
- Either:
onSuccess→onSettled(on success)onError→onSettled(on error)
Mutation Context
The mutation function context provides metadata about the mutation:Resetting Mutations
You can reset a mutation back to its idle state:mutationObserver.ts:119-126:
Retry Behavior
Unlike queries, mutations do not retry by default. You can configure retry behavior:Persisting Mutations
Mutations can be persisted to storage and resumed later, useful for offline-first applications:Optimistic Updates
Optimistic updates allow you to update the UI before the mutation completes:Mutation Scope
Each call tomutate creates a new mutation execution. The mutation state represents the most recent execution:
The mutation observer always tracks the latest mutation execution. Previous executions are not stored in the observer state.