Sub topic 8
Changing server data with useMutation
Queries read data. Mutations change it: creating, updating, or deleting something on the server. This chapter covers useMutation: what it returns, how its lifecycle works, and the mistakes people commonly make with it. It assumes you can already write a useQuery call, you know what a query key is, and you are comfortable with fetch, Promises, and HTTP methods such as POST, PATCH, and DELETE.
Why mutations are a separate hook
A query is declarative. You describe the data you want, and the library decides when to fetch it, reuse it, and refresh it. A mutation is imperative. Nothing should happen until the user acts, and the same action must never run twice by accident because a window regained focus.
For that reason useMutation differs from useQuery in four ways:
- It does not run on mount. It runs only when you call
mutate. - It has no query key, so nothing is cached or deduplicated by key. An optional
mutationKeyexists, but it only identifies the mutation for tooling and shared defaults. - It does not refetch on its own. No focus or reconnect triggers apply.
- It does not retry by default. Query retries default to 3, and mutation retries default to 0, because repeating a non-idempotent request such as a POST can create duplicates.
A first mutation
The mutation function receives one argument, the variables you pass to mutate. Like a query function, it must throw when the request fails. fetch does not reject on a 404 or 500, so check res.ok yourself.
import { useState } from 'react'
import { useMutation, useQueryClient } from '@tanstack/react-query'
type Todo = { id: number; title: string; done: boolean }
async function createTodo(title: string): Promise<Todo> {
const res = await fetch('/api/todos', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ title }),
})
if (!res.ok) throw new Error(`Request failed: ${res.status}`)
return res.json()
}
export function NewTodoForm() {
const queryClient = useQueryClient()
const [title, setTitle] = useState('')
const mutation = useMutation({
mutationFn: createTodo,
onSuccess: () => {
setTitle('')
return queryClient.invalidateQueries({ queryKey: ['todos'] })
},
})
return (
<form
onSubmit={(e) => {
e.preventDefault()
mutation.mutate(title)
}}
>
<input value={title} onChange={(e) => setTitle(e.target.value)} />
<button type="submit" disabled={mutation.isPending || title === ''}>
{mutation.isPending ? 'Saving...' : 'Add'}
</button>
{mutation.isError && <p role="alert">{mutation.error.message}</p>}
</form>
)
}The onSuccess handler calls invalidateQueries, which marks the cached todo list stale so it refetches. The next chapter covers invalidation in detail. For now, note that the mutation changes the server and invalidation tells the cache that its copy is out of date.
The mutation lifecycle
A mutation moves through four statuses. Unlike a query, it starts at idle because nothing has been requested yet.
The hook returns these values for each status:
| Value | Meaning |
|---|---|
| `status` | `'idle'`, `'pending'`, `'success'`, or `'error'` |
| `isIdle`, `isPending`, `isSuccess`, `isError` | Boolean forms of `status` |
| `data` | The value the last successful `mutationFn` returned |
| `error` | The error from the last failed run, otherwise `null` |
| `variables` | The argument passed to the latest `mutate` call |
| `reset` | A function that clears the mutation back to `idle` |
Use isPending to disable the submit button, as in the example above. This prevents double submits from impatient users. Use reset() when a form closes, so an old error message does not appear the next time it opens.
Callbacks
You can attach callbacks in two places, and they behave differently.
import { useMutation, useQueryClient } from '@tanstack/react-query'
function useRenameTodo() {
const queryClient = useQueryClient()
return useMutation({
mutationFn: async ({ id, title }: { id: number; title: string }) => {
const res = await fetch(`/api/todos/${id}`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ title }),
})
if (!res.ok) throw new Error(`Request failed: ${res.status}`)
return res.json()
},
// Hook-level: always runs, even if the component has unmounted.
onSuccess: () => queryClient.invalidateQueries({ queryKey: ['todos'] }),
})
}
function RenameButton({ id, onDone }: { id: number; onDone: () => void }) {
const rename = useRenameTodo()
return (
<button
onClick={() =>
// Call-level: runs only if this component is still mounted.
rename.mutate({ id, title: 'Renamed' }, { onSuccess: onDone })
}
>
Rename
</button>
)
}Hook-level callbacks, set in useMutation, belong to the mutation. Use them for cache work such as invalidation. They run even if the user navigates away before the request finishes.
Call-level callbacks, passed as the second argument to mutate, belong to the component that called it. Use them for UI reactions such as closing a dialog or navigating. They are skipped if the component unmounts first, which is what you want, because the UI they would touch is gone.
When both exist, the hook-level callback runs first, then the call-level one. The full set is onMutate, onSuccess, onError, and onSettled. onSettled runs after either outcome. Optimistic updates, a later chapter, rely on onMutate and onError.
Returning a promise from a callback
If a hook-level callback returns a Promise, the mutation waits for it before it settles. In the first example, onSuccess returns the promise from invalidateQueries. As a result, isPending stays true until the list has refetched, and the button remains disabled until the new todo is visible. Remove the return and the mutation finishes as soon as the POST responds. Neither behavior is wrong, but you should choose one on purpose.
mutate versus mutateAsync
mutate returns nothing. Failures go to error state and the onError callbacks, so you never need a try/catch. This is the right default.
mutateAsync returns a Promise that resolves with the data or rejects with the error. Use it when you need to sequence work in an async function:
import { useMutation } from '@tanstack/react-query'
type Todo = { id: number; title: string }
declare function createTodo(title: string): Promise<Todo>
declare function attachTag(todoId: number, tag: string): Promise<void>
function useCreateTaggedTodo() {
const create = useMutation({ mutationFn: createTodo })
return async (title: string, tag: string) => {
try {
const todo = await create.mutateAsync(title)
await attachTag(todo.id, tag)
} catch (error) {
console.error('Could not create tagged todo', error)
}
}
}If you call mutateAsync without handling the rejection, you get an unhandled Promise rejection. When in doubt, use mutate.
Common errors
- Passing several arguments.
mutationFnreceives a single value. Pass an object, such as{ id, title }, and destructure it. - Forgetting to throw on a bad status. Without the
res.okcheck, a 500 response counts as success andonSuccessruns. - Reading
dataas if it were the server list.mutation.dataholds only the response of that one mutation. It does not update your query data. Update the list through invalidation orsetQueryData. - Expecting a retry. A dropped connection fails the mutation once. Set
retryexplicitly only when the endpoint is idempotent. - Doing cache work in call-level callbacks. If the user navigates away, the invalidation never happens and the list stays stale. Put it in the hook-level callback.
- Reusing one mutation for concurrent calls. Each
useMutationinstance tracks only its latest call. If twomutatecalls overlap,data,status, andvariablesreflect the most recent one. The call-level callbacks of the earlier call do not fire.
Exercise
Exercise
A "Delete" button calls deleteMutation.mutate(id, { onSuccess: () => queryClient.invalidateQueries({ queryKey: ['todos'] }) }). Users report that if they click Delete and immediately navigate to another page, the todo list is still showing the deleted item when they come back. What is the cause, and how do you fix it?
Show answer
The invalidation is in a call-level callback. Call-level callbacks run only while the component that called mutate is still mounted. After the user navigated away, the callback was skipped, so the cached list was never marked stale. Move the invalidation to the hook-level onSuccess in useMutation({ ... }), which runs even after unmount. Keep UI-only reactions, such as closing a dialog, in the call-level callback.