Capítulo 54 de 80

Chapter 54: MutationCache

Core Idea

MutationCache's global onMutate/onError/onSuccess/onSettled callbacks differ from QueryClient's defaultOptions.mutations in one crucial way: they always fire, even when a specific mutation's own callback overrides the default — making them the right place for cross-cutting concerns (global error toasts, logging) that shouldn't be opt-outable per mutation.

Key Concepts

  • Global vs. default callbacks: defaultOptions.mutations.onError (etc.) can be silently overridden by any individual useMutation call; MutationCache's own onError/onSuccess/onSettled/onMutate (set at construction) run unconditionally for every mutation in the cache, alongside whatever the mutation's own callbacks do. All may return a Promise, which is awaited. onMutate here can't return a rollback-context value the way a per-mutation onMutate can.
  • getAll(): returns every Mutation instance currently in the cache — an advanced/rare need, similar to QueryCache.find.
  • subscribe(callback): notified on every mutation-cache update (state change, add, remove) — receives a MutationCacheNotifyEvent; returns an unsubscribe function.
  • clear(): wipes the mutation cache entirely.

Code Examples

const mutationCache = new MutationCache({
  onError: (error) => toast.error(error.message), // fires for every mutation, always
})
const queryClient = new QueryClient({ mutationCache })
  • What it demonstrates: a global error-toast handler that applies to every mutation regardless of what each one's own onError does.

Key Takeaways

  1. Use MutationCache's global callbacks for genuinely universal behavior (error toasts, analytics) — use defaultOptions.mutations when individual mutations should be able to opt out.
  2. getAll()/subscribe() are advanced/introspection tools, not part of normal day-to-day mutation handling.

Connects To

  • Mutations: the per-mutation callback lifecycle these global callbacks layer on top of.
  • QueryCache: the query-side equivalent with the same subscribe/clear shape.