Capítulo 68 de 80

Chapter 68: useMutationState

Core Idea

Gives read access to every mutation in the MutationCache, filtered and transformed via select — the mechanism behind cross-component optimistic-UI (Chapter 30's "via the UI, different component" pattern) and behind reading the latest invocation of a repeatedly-called mutation.

Key Concepts

  • Shape: useMutationState({ filters, select }, queryClient?)filters is a MutationFilters object (commonly { mutationKey, status: 'pending' }); select(mutation) transforms each matching Mutation instance into whatever shape the component needs (e.g. mutation.state.variables).
  • Always returns an array: even filtering to one specific mutationKey, multiple concurrent invocations can coexist — the result reflects all of them, in invocation order.
  • Reading the latest invocation: each mutate() call adds a new entry to the cache, kept for gcTime; to read only the most recent one, take the last element of the returned array (data[data.length - 1]).
  • Cross-component optimistic UI: pairing a mutationKey on the triggering useMutation with useMutationState({ filters: { mutationKey, status: 'pending' }, select: (m) => m.state.variables }) elsewhere in the tree lets any component read a pending mutation's variables without prop drilling or a shared cache write.

Code Examples

// Anywhere in the tree — read variables of all currently-pending 'addTodo' mutations
const variables = useMutationState({
  filters: { mutationKey: ['addTodo'], status: 'pending' },
  select: (mutation) => mutation.state.variables,
})
  • What it demonstrates: reading a pending mutation's variables from a component that didn't trigger it, keyed by a shared mutationKey.

Key Takeaways

  1. This is the enabling mechanism for Optimistic Updates' cross-component "via the UI" variant — pair a mutationKey with a matching filter here.
  2. Always expect an array back, even for a "single" mutation — multiple concurrent invocations are a real possibility this hook accounts for.
  3. To surface only the newest invocation of a repeatable mutation, take the array's last element, not the first.

Connects To

  • Optimistic Updates: the cross-component pattern this hook enables.
  • useMutation: mutationKey, the shared identifier this hook filters on.