React Query: What is a mutation?
12 June 2022 (Updated 22 June 2022)
In a nutshell
In React Query, mutations are used to create, update or delete server-side data. They are also used to perform server side-effects (e.g., call an endpoint that sends an email or that processes a payment).
An example mutation
function App() {
// Unlike useQuery, useMutation doesn't run immediately.
// You must invoke mutation.mutate()
const mutation = useMutation(newTodo => {
return axios.post('/todos', newTodo)
})
return (
<div>
{mutation.isLoading ? (
'Adding todo...'
) : (
<>
{mutation.isError ? (
<div>An error occurred: {mutation.error.message}</div>
) : null}
{mutation.isSuccess ? <div>Todo added!</div> : null}
<button
onClick={() => {
mutation.mutate({ id: new Date(), title: 'Do Laundry' })
}}
>
Create Todo
</button>
</>
)}
</div>
) }
Mutation states
State | Description |
isLoading | The mutation is currently executing. |
isError | The mutation encountered an error. |
isSuccess | The mutation was successful and mutation data is available. |
isIdle | The mutation is currently idle or in a fresh state. |
Mutation information
Property | Description |
data | The mutation data, available only if the mutation is in the isSuccess state. |
error | The error data, availably only if the mutation is in the isError state. |
Mutation lifecycle hooks
You can pass several arguments to the useMutation
hook to perform side-effects at particular stages of the mutation life cycle:
useMutation(addTodo, {
onMutate: variables => {
// A mutation is about to happen!
// Optionally return a context containing data to use when for example rolling back
return { id: 1 }
},
onError: (error, variables, context) => {
// An error happened!
console.log(`rolling back optimistic update with id ${context.id}`)
},
onSuccess: (data, variables, context) => {
// Boom baby!
},
onSettled: (data, error, variables, context) => {
// Error or success... doesn't matter!
},
})
Other notes
- Mutations can become a powerful tool when you use it with the
onSuccess
andinvalidateQueries
methods to invalidate the query cache after updating server data.
Sources
Tagged:
React Query
Thanks for your comment 🙏. Once it's approved, it will appear here.
Leave a comment