useMutation useMutation Write Operations
Last updated: 2026-11-02
useMutation useMutation Write Operations
useMutation manages the async state of write operations (POST, PUT, DELETE): mutate triggers the request, isPending and isError report the progress, and onSuccess invalidates the related queries so the list refreshes on its own. It does not cache data, it only manages this one submission. That division of labour is what makes query and mutation a natural pair. You can also pass callbacks per call, so one hook instance can serve several different forms without sharing their state.
| Group | Data & Engineering |
|---|---|
| Kind | Hook |
| Since | TanStack Query v5 |
ℹ️ Info The editor transpiles JSX to JavaScript and renders the real UI in a sandbox; components mount automatically — no manual render call needed.
📝 Syntax
import { useMutation, useQueryClient } from '@tanstack/react-query'
const qc = useQueryClient()
const mutation = useMutation({
mutationFn: newTodo => fetch('/api/todos', {
method: 'POST',
body: JSON.stringify(newTodo)
}).then(r => r.json()),
onSuccess: () => {
qc.invalidateQueries({ queryKey: ['todos'] }) // the list turns stale -> it refetches itself
}
})
mutation.mutate({ title: 'New task' }) // fire the submission
⚙️ Parameters
| mutationFn | Required. The async function that performs the write operation; the variables passed to mutate(variables) arrive as its argument. |
|---|---|
| onSuccess / onError | Callback hooks: invalidate queries after a success, show a message after a failure; they can also be overridden per call with mutate(v, { onSuccess }). |
Returns:Returns { mutate, isPending, isError, data, error }: mutate(variables) fires the request (it returns no Promise), while mutateAsync does return a Promise.
▶ Example
The example runs out of the box: it auto-renders when expanded, and edits take effect instantly.
Output:
The submit button turns into "Saving…" and stays disabled for one second, then the list gains an entry and a success message appears - the full flow of mutate, isPending and onSuccess (simulated demo).