Skip to content
Tutorials Center
My learning

Topics

Lesson 15 of 38 ยท Mutations

Mutation State, Keys and Scopes

Observe mutations from anywhere with useIsMutating and useMutationState, name them with mutationKey, and run related mutations one at a time with scope.

A mutation's state lives in the component that calls useMutation. That is fine for a form's own submit button, but real apps often need to know about saves from elsewhere: a spinner in the header that says "Saving...", a list that shows pending items in grey, a warning before the user closes the tab. TanStack Query exposes every mutation through the MutationCache, and a few small hooks let you read it. This lesson also shows how to name mutations and how to make related ones run in order.

mutationKey

Mutations do not need a key, but you can give one. It is a plain array, like a query key, and its main job is to let you find mutations later.

JSX
useMutation({
  mutationKey: ["todos", "add"],
  mutationFn: createTodo,
});

It also lets you set shared defaults once, for example for offline persistence: queryClient.setMutationDefaults(["todos", "add"], { mutationFn: createTodo }).

useIsMutating

useIsMutating returns the number of mutations currently pending, optionally filtered by key. It is the hook behind a global "Saving..." indicator.

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

function GlobalSavingIndicator() {
  const count = useIsMutating();                              // all mutations
  const todoCount = useIsMutating({ mutationKey: ["todos"] }); // prefix match
  return count > 0 ? <span>Saving {count}...</span> : null;
}

Its sibling for queries is useIsFetching, which counts running requests, and is the typical source for a top-of-page loading bar. Both only count; they never cause a fetch.

useMutationState

useMutationState gives you the state objects of mutations, with a filters argument to choose which ones and a select function to pick what you need from each. It is perfect for showing pending items from a different component than the one that fired them.

A header that watches mutations

Press Add a few times quickly. The header counts the pending saves and the grey list shows their names, all from components that never called useMutation themselves. The Form hook is single-call: each new mutate replaces what it tracks, but the cache still knows about every one of them.

Filter properties you can use: mutationKey, status ("idle", "pending", "success", "error"), exact, and a custom predicate.

useMutationState returns data about mutations that are still in the cache. Finished mutations are garbage collected after gcTime (five minutes by default) once no hook observes them, so use it for "recent" state, not as a log.

By default, mutations run in parallel. If a user taps "like" and "unlike" rapidly, two requests are in flight and the server might apply them in the wrong order. The scope option solves it: mutations with the same scope id run serially, one after the other, in the order they were started.

JSX
useMutation({
  mutationFn: toggleLike,
  scope: { id: "like-post-17" },
});

Mutations without a scope run in parallel as usual. Choose the scope id so it groups the operations that must not overlap, such as one id per document or per resource.

Parallel versus serial mutations

Fire both lanes. Without a scope, all three start together and end together. With a scope, each one starts after the previous finishes, so the timestamps step by roughly 500 ms. (Calling mutate three times on one hook is only for the demo; per-call callbacks would fire for the latest call only.)

Scopes also help offline

When the device is offline, mutations are paused and resume when the connection returns. With a scope, they resume one at a time in the original order, which is exactly what an offline-first editor needs.

Other useful reads

  • queryClient.isMutating({ mutationKey }) is the non-hook form of useIsMutating.
  • useMutation returns isPaused and failureCount for the current call.
  • queryClient.getMutationCache().getAll() lists every mutation, handy in DevTools-style debugging code (see DevTools).

Mutations stay simple once you know these four tools: the hook's own state, useIsMutating for counts, useMutationState for details and scope for ordering. In the next chapter we turn to the other half of the design: how long cached data is trusted. Start with Stale Time and Garbage Collection Time.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does useIsMutating() return?

    It is a count, optionally filtered by mutationKey. Use it for global saving indicators.
  2. 2. Two mutations with the same scope id are started together. What happens?

    Scope ids make related mutations run serially.
  3. 3. Which hook returns details (such as variables) of mutations fired elsewhere?

    useMutationState takes filters and a select function over the mutation cache.
  4. 4. How long do finished mutations stay in the cache without observers?

    Unobserved mutations are garbage collected after gcTime.

Summary

  • mutationKey names mutations so they can be filtered and given shared defaults.
  • useIsMutating counts pending mutations; useMutationState returns their state objects.
  • Both read the MutationCache, so any component can observe a mutation fired anywhere.
  • scope: { id } serializes related mutations, which also preserves order after offline pauses.
  • Finished, unobserved mutations disappear after gcTime.

Next: Stale Time and Garbage Collection Time