Open History to see the last commit
1---
2id: useMutation
3title: useMutation
4redirect_from:
5 - framework/react/reference/useMutation
6---
7β
8<!-- DO NOT EDIT: this page is autogenerated from the type comments -->
9β
10```ts
11function useMutation<TData = unknown, TError = Error, TVariables = void, TOnMutateResult = unknown>(options: UseMutationOptions<TData, TError, TVariables, TOnMutateResult>, queryClient?: QueryClient): UseMutationResult<TData, TError, TVariables, TOnMutateResult>;
12```
13β
14Defined in: [packages/react-query/src/useMutation.ts:187](https://github.com/TanStack/query/blob/main/packages/react-query/src/useMutation.ts#L187)
15β
16Unlike queries, mutations are typically used to create/update/delete data or perform server side-effects.
17`useMutation` is the hook for that.
18β
19## Type Parameters
20β
21### TData
22β
23`TData` = `unknown`
24β
25### TError
26β
27`TError` = `Error`
28β
29### TVariables
30β
31`TVariables` = `void`
32β
33### TOnMutateResult
34β
35`TOnMutateResult` = `unknown`
36β
37## Parameters
38β
39### options
40β
41[`UseMutationOptions`](../interfaces/UseMutationOptions.md)\<`TData`, `TError`, `TVariables`, `TOnMutateResult`\>
42β
43The [UseMutationOptions](../interfaces/UseMutationOptions.md) to use β everything you can pass to `useMutation`.
44β
45<a id="options-properties"></a>
46β
47#### `options` properties
48β
49| Property | Type | Default value | Description |
50| ------ | ------ | ------ | ------ |
51| <a id="options-property-gctime"></a> `gcTime?` | `number` | `undefined` | The time in milliseconds that an unused/inactive mutation remains in memory before it is garbage collected. Defaults to `5 * 60 * 1000` (5 minutes), or `Infinity` during SSR. |
52| <a id="options-property-meta"></a> `meta?` | `Record`\<`string`, `unknown`\> | `undefined` | Additional payload to be stored on the mutation cache entry. Use it to pass information that can be read wherever the `mutation` is available, such as the `onError` and `onSuccess` callbacks of the `MutationCache`. |
53| <a id="options-property-mutationfn"></a> `mutationFn?` | (`variables`: `TVariables`, `context`: [`MutationFunctionContext`](../type-aliases/MutationFunctionContext.md)) => `Promise`\<`TData`\> | `undefined` | The function that performs the asynchronous task this mutation runs. Required, unless a default mutation function has been set for the matching `mutationKey` via `queryClient.setMutationDefaults`. Receives the `variables` passed to `mutate`, and a [MutationFunctionContext](../type-aliases/MutationFunctionContext.md) holding the `QueryClient`, the `mutationKey` and `meta`. Must return a promise that resolves the mutation's data. |
54| <a id="options-property-mutationkey"></a> `mutationKey?` | readonly `unknown`[] | `undefined` | The key to use for this mutation. Optional, but required to inherit defaults registered with `queryClient.setMutationDefaults`, and to match this mutation with `useMutationState` or `queryClient.isMutating`. |
55| <a id="options-property-networkmode"></a> `networkMode?` | `"online"` \| `"always"` \| `"offlineFirst"` | `'online'` | Controls whether a mutation is allowed to run based on the current network connectivity. **See** [Network Mode](https://tanstack.com/query/latest/docs/framework/react/guides/network-mode) for more information. |
56| <a id="options-property-onerror"></a> `onError?` | (`error`: `TError`, `variables`: `TVariables`, `onMutateResult`: `TOnMutateResult` \| `undefined`, `context`: [`MutationFunctionContext`](../type-aliases/MutationFunctionContext.md)) => `unknown` | `undefined` | This function fires when the mutation encounters an error, and is passed the error. If a promise is returned, it is awaited before `onSettled` runs. |
57| <a id="options-property-onmutate"></a> `onMutate?` | (`variables`: `TVariables`, `context`: [`MutationFunctionContext`](../type-aliases/MutationFunctionContext.md)) => `TOnMutateResult` \| `Promise`\<`TOnMutateResult`\> | `undefined` | This function fires before the mutation function runs, and receives the same variables. Useful for optimistic updates applied in the hope that the mutation succeeds. The value it returns is passed to `onSuccess`, `onError` and `onSettled` as `onMutateResult`, which is where an optimistic update is usually rolled back. If a promise is returned, it is awaited before the mutation function runs. |
58| <a id="options-property-onsettled"></a> `onSettled?` | (`data`: `TData` \| `undefined`, `error`: `TError` \| `null`, `variables`: `TVariables`, `onMutateResult`: `TOnMutateResult` \| `undefined`, `context`: [`MutationFunctionContext`](../type-aliases/MutationFunctionContext.md)) => `unknown` | `undefined` | This function fires when the mutation either succeeds or errors, and is passed either the data or the error. If a promise is returned, it is awaited before the mutation settles. |
59| <a id="options-property-onsuccess"></a> `onSuccess?` | (`data`: `TData`, `variables`: `TVariables`, `onMutateResult`: `TOnMutateResult`, `context`: [`MutationFunctionContext`](../type-aliases/MutationFunctionContext.md)) => `unknown` | `undefined` | This function fires when the mutation succeeds, and is passed the mutation's result. If a promise is returned, it is awaited before `onSettled` runs. |
60| <a id="options-property-retry"></a> `retry?` | \| `number` \| `false` \| `true` \| ((`failureCount`: `number`, `error`: `TError`) => `boolean`) | `0` | If `false`, failed mutations will not retry by default. If `true`, failed mutations will retry infinitely. If set to an integer number, e.g. 3, failed mutations will retry until the failed mutation count meets that number. If set to a function `(failureCount, error) => boolean` failed mutations will retry until the function returns false. |
61| <a id="options-property-retrydelay"></a> `retryDelay?` | `number` \| ((`failureCount`: `number`, `error`: `TError`) => `number`) | `undefined` | This function receives a `retryAttempt` integer and the actual Error and returns the delay to apply before the next attempt in milliseconds. Defaults to a function that applies exponential backoff, capped at 30 seconds. |
62| <a id="options-property-scope"></a> `scope?` | [`MutationScope`](../type-aliases/MutationScope.md) | `undefined` | Controls whether this mutation runs alongside others or waits its turn. Mutations sharing the same `scope.id` run serially, in the order they were started. Without a scope, a mutation runs as soon as it is triggered. |
63| <a id="options-property-throwonerror"></a> `throwOnError?` | `boolean` \| ((`error`: `TError`) => `boolean`) | `false` | Whether errors should be thrown instead of setting the `error` property. If set to `true`, all errors will be thrown to the nearest error boundary. If set to a function, it will be passed the error and should return a boolean indicating whether to throw the error (`true`) or return it as state (`false`). |
64β
65### queryClient?
66β
67[`QueryClient`](../classes/QueryClient.md)
68β
69Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will
70be used.
71β
72## Returns
73β
74[`UseMutationResult`](../type-aliases/UseMutationResult.md)\<`TData`, `TError`, `TVariables`, `TOnMutateResult`\>
75β
76`mutate`/`mutateAsync` also accept per-call `onSuccess`/`onError`/`onSettled` callbacks as a second
77argument, useful for triggering call-site side effects (e.g. navigation) without coupling them to the shared
78mutation definition. Hook-level callbacks (passed to `options`) fire for every mutation; per-call callbacks
79fire only for the latest call you've made, and only while the component is still mounted β unmounting before
80the mutation settles removes the subscription and prevents them from firing.
81β
82<a id="result-properties"></a>
83β
84### Result properties
85β
86Built from [`MutationObserverBaseResult`](../interfaces/MutationObserverBaseResult.md#properties). See the type above for what it changes.
87β
88## Throws
89β
90The mutation error, when `throwOnError` is `true` or returns `true` for it, so that it is
91thrown to the nearest error boundary.
92β
93## See
94β
95[mutationOptions](mutationOptions.md) to share these options across multiple `useMutation` call sites, or to look
96the mutation up elsewhere via its `mutationKey` (e.g. with `useMutationState`).
97β
98## Examples
99β
100```tsx
101import { useMutation, useQueryClient } from '@tanstack/react-query'
102β
103function AddTodo() {
104 const queryClient = useQueryClient()
105β
106 const addMutation = useMutation({
107 mutationFn: addTodo,
108 onSuccess: () => queryClient.invalidateQueries({ queryKey: ['todos'] }),
109 })
110β
111 return (
112 <button
113 onClick={() =>
114 addMutation.mutate('Item', {
115 onError: (error) => console.error('Failed to add item:', error),
116 })
117 }
118 >
119 Add
120 </button>
121 )
122}
123```
124β
125Rendering the mutation's own state, rather than just firing it off:
126```tsx
127import { useMutation, useQueryClient } from '@tanstack/react-query'
128β
129function AddTodo() {
130 const queryClient = useQueryClient()
131β
132 const addMutation = useMutation({
133 mutationFn: addTodo,
134 onSuccess: () => queryClient.invalidateQueries({ queryKey: ['todos'] }),
135 })
136β
137 return (
138 <div>
139 {addMutation.isPending ? (
140 'Adding todo...'
141 ) : (
142 <>
143 {addMutation.isError ? (
144 <div>An error occurred: {addMutation.error.message}</div>
145 ) : null}
146 <button onClick={() => addMutation.mutate('Item')}>Add</button>
147 </>
148 )}
149 </div>
150 )
151}
152```
153β
154Optimistic update via `onMutate`, rolling back on `onError`:
155```tsx
156import { useMutation, useQueryClient } from '@tanstack/react-query'
157β
158function AddTodo() {
159 const queryClient = useQueryClient()
160β
161 const addMutation = useMutation({
162 mutationFn: addTodo,
163 onMutate: async (newTodo) => {
164 await queryClient.cancelQueries({ queryKey: ['todos'] })
165 const previousTodos = queryClient.getQueryData<Array<string>>(['todos'])
166β
167 queryClient.setQueryData<Array<string>>(['todos'], (old) => [
168 ...(old ?? []),
169 newTodo,
170 ])
171β
172 // Passed to `onError` as `onMutateResult` if the mutation fails.
173 return { previousTodos }
174 },
175 onError: (_err, _newTodo, onMutateResult) => {
176 queryClient.setQueryData(['todos'], onMutateResult?.previousTodos)
177 },
178 onSettled: () => {
179 queryClient.invalidateQueries({ queryKey: ['todos'] })
180 },
181 })
182β
183 return (
184 <button onClick={() => addMutation.mutate('Item')}>Add</button>
185 )
186}
187```
188β
189Callbacks passed per call to `mutate` only fire for the last call β `mutateAsync` gives you a
190promise per call instead, so you can wait for all of them when they succeed:
191```tsx
192import { useMutation, useQueryClient } from '@tanstack/react-query'
193β
194function AddTodos() {
195 const queryClient = useQueryClient()
196β
197 const addMutation = useMutation({
198 mutationFn: addTodo,
199 onSuccess: () => queryClient.invalidateQueries({ queryKey: ['todos'] }),
200 })
201β
202 async function handleAddAll(todos: Array<string>) {
203 try {
204 await Promise.all(todos.map((todo) => addMutation.mutateAsync(todo)))
205 } catch (error) {
206 console.error('Failed to add todos:', error)
207 }
208 }
209β
210 return (
211 <button onClick={() => handleAddAll(['Todo 1', 'Todo 2', 'Todo 3'])}>
212 Add all
213 </button>
214 )
215}
216```
217β
218If some of the mutations above can fail independently of the others, and you want to know which ones
219did β rather than losing that information the moment the first one rejects β swap `Promise.all` for
220`Promise.allSettled`:
221```tsx
222import { useMutation, useQueryClient } from '@tanstack/react-query'
223β
224function AddTodos() {
225 const queryClient = useQueryClient()
226β
227 const addMutation = useMutation({
228 mutationFn: addTodo,
229 onSuccess: () => queryClient.invalidateQueries({ queryKey: ['todos'] }),
230 })
231β
232 async function handleAddAll(todos: Array<string>) {
233 const addResults = await Promise.allSettled(
234 todos.map((todo) => addMutation.mutateAsync(todo)),
235 )
236β
237 addResults.forEach((addResult, index) => {
238 if (addResult.status === 'rejected') {
239 console.error(`Failed to add "${todos[index]}":`, addResult.reason)
240 }
241 })
242 }
243β
244 return (
245 <button onClick={() => handleAddAll(['Todo 1', 'Todo 2', 'Todo 3'])}>
246 Add all
247 </button>
248 )
249}
250```