Skip to main content

useMutation

Hook to mutate data on the server.

const mutation = useMutation(options)

Options

PropertyTypeDefaultDescription
mutationFn`(variables) => Promise<T>`RequiredThe mutation function.
mutationKey`unknown[]`-Optional key (useful for devtools).
onMutate`(variables) => Promise<Context>`-Fired before mutationFn. Useful for optimistic updates.
onSuccess`(data, variables, context)`-Fired on success.
onError`(err, variables, context)`-Fired on error.
onSettled`(data, err, variables)`-Fired on success or error.
invalidatesTags`string[]`-Automatically invalidates these tags on success.
optimistic`object`-Declarative optimistic update config.

Optimistic Config

{
queryKey: ['key'],
update: (variables, oldData) => newData
}

Returns

PropertyTypeDescription
mutate`(variables) => void`Trigger the mutation.
mutateAsync`(variables) => Promise<T>`Trigger and await the result.
data`T`The response data.
error`Error`The error object.
isLoading`boolean`True if mutation is in flight.
status`'idle' | 'pending' | 'success' | 'error'`Current status.
reset`() => void`Reset state to 'idle'.