Open History to see the last commit
1---
2id: useMutation
3title: useMutation
4redirect_from:
5 - framework/react/reference/useMutation
6---
7β
8```ts
9function useMutation<TData, TError, TVariables, TOnMutateResult>(options: UseMutationOptions<TData, TError, TVariables, TOnMutateResult>, queryClient?: QueryClient): UseMutationResult<TData, TError, TVariables, TOnMutateResult>;
10```
11β
12Defined in: [packages/react-query/src/useMutation.ts:191](https://github.com/TanStack/query/blob/main/packages/react-query/src/useMutation.ts#L191)
13β
14Unlike queries, mutations are typically used to create/update/delete data or perform server side-effects.
15`useMutation` is the hook for that.
16β
17## Type Parameters
18β
19### TData
20β
21`TData` = `unknown`
22β
23### TError
24β
25`TError` = `Error`
26β
27### TVariables
28β
29`TVariables` = `void`
30β
31### TOnMutateResult
32β
33`TOnMutateResult` = `unknown`
34β
35## Parameters
36β
37### options
38β
39[`UseMutationOptions`](../interfaces/UseMutationOptions.md)\<`TData`, `TError`, `TVariables`, `TOnMutateResult`\>
40β
41The [UseMutationOptions](../interfaces/UseMutationOptions.md) to use β everything you can pass to `useMutation`.
42β
43### queryClient?
44β
45[`QueryClient`](../classes/QueryClient.md)
46β
47Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will
48be used.
49β
50## Returns
51β
52[`UseMutationResult`](../type-aliases/UseMutationResult.md)\<`TData`, `TError`, `TVariables`, `TOnMutateResult`\>
53β
54`mutate`/`mutateAsync` also accept per-call `onSuccess`/`onError`/`onSettled` callbacks as a second
55argument, useful for triggering call-site side effects (e.g. navigation) without coupling them to the shared
56mutation definition. Hook-level callbacks (passed to `options`) fire for every mutation; per-call callbacks
57fire only for the latest call you've made, and only while the component is still mounted β unmounting before
58the mutation settles removes the subscription and prevents them from firing.
59β
60## See
61β
62[mutationOptions](mutationOptions.md) to share these options across multiple `useMutation` call sites, or to look
63the mutation up elsewhere via its `mutationKey` (e.g. with `useMutationState`).
64β
65## Examples
66β
67```tsx
68import { useMutation, useQueryClient } from '@tanstack/react-query'
69β
70function AddTodo() {
71 const queryClient = useQueryClient()
72β
73 const addMutation = useMutation({
74 mutationFn: addTodo,
75 onSuccess: () => queryClient.invalidateQueries({ queryKey: ['todos'] }),
76 })
77β
78 return (
79 <button
80 onClick={() =>
81 addMutation.mutate('Item', {
82 onError: (error) => console.error('Failed to add item:', error),
83 })
84 }
85 >
86 Add
87 </button>
88 )
89}
90```
91β
92Rendering the mutation's own state, rather than just firing it off:
93```tsx
94import { useMutation, useQueryClient } from '@tanstack/react-query'
95β
96function AddTodo() {
97 const queryClient = useQueryClient()
98β
99 const addMutation = useMutation({
100 mutationFn: addTodo,
101 onSuccess: () => queryClient.invalidateQueries({ queryKey: ['todos'] }),
102 })
103β
104 return (
105 <div>
106 {addMutation.isPending ? (
107 'Adding todo...'
108 ) : (
109 <>
110 {addMutation.isError ? (
111 <div>An error occurred: {addMutation.error.message}</div>
112 ) : null}
113 <button onClick={() => addMutation.mutate('Item')}>Add</button>
114 </>
115 )}
116 </div>
117 )
118}
119```
120β
121Optimistic update via `onMutate`, rolling back on `onError`:
122```tsx
123import { useMutation, useQueryClient } from '@tanstack/react-query'
124β
125function AddTodo() {
126 const queryClient = useQueryClient()
127β
128 const addMutation = useMutation({
129 mutationFn: addTodo,
130 onMutate: async (newTodo) => {
131 await queryClient.cancelQueries({ queryKey: ['todos'] })
132 const previousTodos = queryClient.getQueryData<Array<string>>(['todos'])
133β
134 queryClient.setQueryData<Array<string>>(['todos'], (old) => [
135 ...(old ?? []),
136 newTodo,
137 ])
138β
139 // Passed to `onError` as `onMutateResult` if the mutation fails.
140 return { previousTodos }
141 },
142 onError: (_err, _newTodo, onMutateResult) => {
143 queryClient.setQueryData(['todos'], onMutateResult?.previousTodos)
144 },
145 onSettled: () => {
146 queryClient.invalidateQueries({ queryKey: ['todos'] })
147 },
148 })
149β
150 return (
151 <button onClick={() => addMutation.mutate('Item')}>Add</button>
152 )
153}
154```
155β
156Callbacks passed per call to `mutate` only fire for the last call β `mutateAsync` gives you a
157promise per call instead, so you can wait for all of them when they succeed:
158```tsx
159import { useMutation, useQueryClient } from '@tanstack/react-query'
160β
161function AddTodos() {
162 const queryClient = useQueryClient()
163β
164 const addMutation = useMutation({
165 mutationFn: addTodo,
166 onSuccess: () => queryClient.invalidateQueries({ queryKey: ['todos'] }),
167 })
168β
169 async function handleAddAll(todos: Array<string>) {
170 try {
171 await Promise.all(todos.map((todo) => addMutation.mutateAsync(todo)))
172 } catch (error) {
173 console.error('Failed to add todos:', error)
174 }
175 }
176β
177 return (
178 <button onClick={() => handleAddAll(['Todo 1', 'Todo 2', 'Todo 3'])}>
179 Add all
180 </button>
181 )
182}
183```
184β
185If some of the mutations above can fail independently of the others, and you want to know which ones
186did β rather than losing that information the moment the first one rejects β swap `Promise.all` for
187`Promise.allSettled`:
188```tsx
189import { useMutation, useQueryClient } from '@tanstack/react-query'
190β
191function AddTodos() {
192 const queryClient = useQueryClient()
193β
194 const addMutation = useMutation({
195 mutationFn: addTodo,
196 onSuccess: () => queryClient.invalidateQueries({ queryKey: ['todos'] }),
197 })
198β
199 async function handleAddAll(todos: Array<string>) {
200 const addResults = await Promise.allSettled(
201 todos.map((todo) => addMutation.mutateAsync(todo)),
202 )
203β
204 addResults.forEach((addResult, index) => {
205 if (addResult.status === 'rejected') {
206 console.error(`Failed to add "${todos[index]}":`, addResult.reason)
207 }
208 })
209 }
210β
211 return (
212 <button onClick={() => handleAddAll(['Todo 1', 'Todo 2', 'Todo 3'])}>
213 Add all
214 </button>
215 )
216}
217```