Skip to content
Tutorials Center
My learning

Topics

Lesson 13 of 38 ยท Mutations

Mutation Callbacks and Lifecycle

Learn the mutation lifecycle: onMutate, onSuccess, onError and onSettled, their order and arguments, hook-level versus per-call callbacks, and what happens on unmount.

A mutation goes through a predictable life: it starts, the request runs, and it ends in success or failure. TanStack Query lets you hook into each moment with four callbacks. Knowing their order, their arguments and the difference between callbacks placed on the hook and callbacks placed on mutate removes most surprises, especially when you add optimistic updates later in the course.

The four callbacks

JSX
useMutation({
  mutationFn: saveTodo,
  onMutate: (variables) => { /* before the request */ },
  onSuccess: (data, variables, onMutateResult) => { /* request succeeded */ },
  onError: (error, variables, onMutateResult) => { /* request failed */ },
  onSettled: (data, error, variables, onMutateResult) => { /* always, at the end */ },
});
Callback When Typical use
onMutate Right after mutate(), before mutationFn Snapshot data, optimistic update, validation
onSuccess The function resolved Invalidate, navigate, show a toast
onError The function rejected Roll back, show an error
onSettled After success or error Cleanup, final refetch

The value you return from onMutate is passed as the last argument to onSuccess, onError and onSettled. It is the standard way to carry a snapshot from "before" to "rollback". In recent v5 versions this argument is documented as onMutateResult, and older 5.x releases call it context; the position is the same.

Watching the order

This demo logs every callback, both from the hook and from the call to mutate. Run it with success, then with failure.

The callback order

You will see the hook-level callbacks first, then the per-call ones, and onSettled last in each group. Importantly, hook callbacks run before call callbacks, and onMutate exists only on the hook (it is not accepted by mutate).

Hook-level versus per-call callbacks

Defined on useMutation Defined on mutate(vars, { ... })
Runs for Every call That call only
Runs if the component unmounted Yes No
Has onMutate Yes No
Typical use Cache work (invalidate, rollback) UI work (reset a form, close a modal, navigate)

The unmount rule is the practical one. If the user leaves the page while a save is in flight, you still want the cache to be invalidated (hook-level), but you no longer want to call navigate() or close a modal that does not exist (call-level, which is skipped automatically). Splitting responsibilities along that line gives you correct behavior without any isMounted checks.

A related detail: per-call callbacks only fire for the latest call. If a user clicks Save twice quickly, only the second call's callbacks run, while hook-level callbacks run for both.

Callbacks can be async

If a callback returns a promise, the mutation waits for it before moving to the next step. That is what made returning invalidateQueries meaningful in the previous lesson. The same applies to onMutate: the request does not start until its promise resolves, which matters for optimistic updates, where you await cancelQueries before writing to the cache.

JSX
useMutation({
  mutationFn: saveTodo,
  onMutate: async (newTodo) => {
    await queryClient.cancelQueries({ queryKey: ["todos"] });
    const previous = queryClient.getQueryData(["todos"]);
    queryClient.setQueryData(["todos"], (old) => [...old, newTodo]);
    return { previous };
  },
  onError: (err, newTodo, onMutateResult) => {
    queryClient.setQueryData(["todos"], onMutateResult.previous);
  },
  onSettled: () => queryClient.invalidateQueries({ queryKey: ["todos"] }),
});

This is only a preview; the optimistic chapter walks through it step by step.

Errors thrown inside callbacks

If onMutate throws, the request is not sent and the mutation goes to onError. If onSuccess throws or rejects, the mutation ends in the error state, even though the server accepted the request, and onError runs. Keep callbacks small and put risky UI code (navigation, toasts) in a place where a failure will not mark a successful save as failed.

Global callbacks with the MutationCache

For cross-cutting behavior, such as a toast for every failed mutation, attach callbacks to the client's cache once instead of repeating them:

JavaScript
import { MutationCache, QueryClient } from "@tanstack/react-query";

const queryClient = new QueryClient({
  mutationCache: new MutationCache({
    onError: (error, variables, onMutateResult, mutation) => {
      showToast("Something went wrong: " + error.message);
    },
  }),
});

These run in addition to the hook-level callbacks, and they run first. In v5 the same idea exists on QueryCache for queries (onError), because useQuery no longer has its own onError; see Retries and Error Handling.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. In which order do the callbacks run for a failing mutation?

    onMutate runs before the request, then onError on failure, then onSettled.
  2. 2. What does the value returned from onMutate become?

    It is the way to carry a snapshot, for example for a rollback in onError.
  3. 3. The component unmounts while the request is in flight. Which callbacks still run?

    Per-call callbacks are skipped after unmount; hook-level callbacks always run.
  4. 4. Where does onMutate live?

    mutate() accepts onSuccess, onError and onSettled, but not onMutate.

Summary

  • Lifecycle: onMutate, then the function, then onSuccess or onError, then onSettled.
  • What onMutate returns is handed to the later callbacks, which enables rollbacks.
  • Hook callbacks always run (cache work); per-call callbacks are skipped after unmount (UI work).
  • Callbacks may return promises, and the mutation waits for them.
  • Use MutationCache callbacks for app-wide behavior such as error toasts.

Next: Updating the Cache from Responses