Skip to content
Tutorials Center
My learning

Topics

Lesson 11 of 38 ยท Mutations

Mutations with useMutation

Send changes to the server with useMutation: mutationFn, mutate versus mutateAsync, isPending, error and reset, and how mutations differ from queries.

Queries read data. Mutations change it: creating a todo, updating a profile, deleting a comment, logging in. TanStack Query handles them with a separate hook, useMutation, because they behave differently from queries in important ways. In this lesson you learn the basic shape of a mutation, how to trigger it, and how to read its state. The following lessons connect mutations back to the cache.

Queries versus mutations

Query Mutation
Purpose Read Write (side effects)
Runs Automatically, when declared Only when you call mutate
Identified by A key, shared and cached Nothing shared; each call is its own
Retries 3 times by default 0 times by default
Result Cached, refetched Kept only while the hook is mounted

Running a write twice can have real consequences (two orders, two emails), which is why mutations never run on their own and do not retry unless you say so.

The basic shape

JSX
import { useMutation } from "@tanstack/react-query";

function AddTodo() {
  const mutation = useMutation({
    mutationFn: (title) =>
      fetch("/api/todos", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ title }),
      }).then((r) => {
        if (!r.ok) throw new Error("HTTP " + r.status);
        return r.json();
      }),
  });

  return (
    <button onClick={() => mutation.mutate("Buy milk")} disabled={mutation.isPending}>
      {mutation.isPending ? "Saving..." : "Add todo"}
    </button>
  );
}

mutationFn receives one argument, the variables you pass to mutate. If you need several values, pass an object: mutate({ id, title }). Like a queryFn, it must return a promise and must throw (or reject) on failure.

State of a mutation

useMutation returns an object with the state of the latest call:

Field Meaning
status "idle", "pending", "error" or "success"
isIdle, isPending, isError, isSuccess Booleans for each status
data The value the function resolved with
error The error that was thrown
variables What was passed to the latest mutate
mutate Fire and forget (returns nothing)
mutateAsync Returns a promise
reset Go back to idle, clearing data and error

Try it with a fake server. Every third save fails, so you can see all four statuses.

A mutation with all four statuses

Press Save three times and watch the status cycle through pending, success, and error on the third attempt. reset() returns the hook to idle, which is useful for dismissing an error message.

mutate versus mutateAsync

  • mutate(variables, options) returns nothing. Errors do not need a try/catch, because they land in mutation.error and in callbacks. This is the right choice nearly all the time.
  • mutateAsync(variables) returns a promise that resolves with the result or rejects with the error. Use it when you need to await the result: chaining several mutations, or running code after success inside the same function. You are then responsible for catching the rejection.
JSX
async function handleSubmit() {
  try {
    const todo = await mutation.mutateAsync({ title });
    navigate("/todos/" + todo.id);
  } catch (error) {
    // already shown by mutation.error; log or ignore here
  }
}

An unhandled mutateAsync rejection is an unhandled promise rejection in the browser, so prefer mutate unless you really need the promise.

Per-call callbacks

Both mutate and mutateAsync accept a second argument with onSuccess, onError and onSettled. These run only for that call, and only if the component is still mounted:

JSX
mutation.mutate(newTodo, {
  onSuccess: (data) => showToast("Saved " + data.title),
  onError: (error) => showToast(error.message),
});

The hook itself also takes callbacks, which run for every call and even if the component unmounted. The next lesson compares the two in detail. First, you need to know what to do with the result, and that is the subject of Invalidating After Mutations.

Mutations do not share state

Unlike queries, two components calling useMutation do not share anything, even with the same function. Each hook instance tracks its own latest call. If you need to observe mutations from elsewhere (for example a global "saving..." indicator), useIsMutating and useMutationState do that, and they are covered in Mutation State and Scopes.

Retries and offline behavior

A mutation does not retry by default (retry: 0). You can opt in for idempotent operations:

JSX
useMutation({ mutationFn: saveTodo, retry: 2, retryDelay: 1000 });

If the device is offline, a mutation is paused (isPaused is true) until the connection returns, then it continues. Be careful with retries on non-idempotent writes such as "charge the card": a retry after a timeout might repeat an action that actually succeeded. Use idempotency keys on the server if you need that safety.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. When does a mutation run?

    Mutations are explicit side effects, so they never run automatically.
  2. 2. How many arguments does mutationFn receive?

    Pass an object as the variables when you need several values.
  3. 3. What is a good reason to use mutateAsync over mutate?

    mutateAsync returns a promise you can await. You must then catch rejections yourself.
  4. 4. What is the default retry count for mutations?

    Writes may have side effects, so mutations do not retry unless you set retry.

Summary

  • useMutation({ mutationFn }) returns mutate, mutateAsync and the state of the latest call.
  • mutationFn receives a single variables argument and must throw on failure.
  • Prefer mutate; use mutateAsync only when you need to await, and catch its errors.
  • Mutations do not run automatically, do not retry by default and are not cached like queries.
  • Per-call callbacks passed to mutate run only if the component is still mounted.

Next: Invalidating Queries After Mutations