Skip to main content

mutationKey

Description: Defines a unique key to identify the mutation in the cache. If not provided, a unique key is automatically generated using useId.

  • How To: Pass mutationKey in the useMutation options. This key can be used to track the mutation state globally or via other hooks like useIsMutating.
    // Explicit mutation key
    const { mutate } = useMutation({
    mutationKey: 'update-user-profile'
    });

    // Tracking elsewhere
    const isUpdating = useIsMutating('update-user-profile');
  • Best Practice: Use a specific mutationKey when you need to monitor the mutation's state from outside the component that initiated it, or when you want to ensure that multiple instances of the same mutation share the same state. This is especially useful for global actions like "logging in" or "updating cart".

Deep Dive: How mutationKey works step by step

Example:

function AddToCartButton({ productId }) {
const { mutate } = useMutation({
mutationKey: ['add-to-cart', productId]
});

return <button onClick={() => mutate(() => cartApi.add(productId))}>Add to Cart</button>;
}

function CartIcon({ productId }) {
// Component in the header observing a specific product's mutation
const isAdding = useIsMutating(['add-to-cart', productId]);
return <div>{isAdding ? <Spinner /> : <CartBadge />}</div>;
}

What happens step by step:

  1. AddToCartButton calls mutate()
    • useMutation uses the provided ['add-to-cart', productId] as the key.
    • It registers the mutation in the global mutateCache.
  2. CartIcon is notified
    • useIsMutating is subscribed to the global mutateCache.
    • It sees a mutation with key ['add-to-cart', productId] is in 'fetching' status.
    • It returns true, and the CartIcon re-renders with a spinner.
  3. Mutation completes
    • DataClient updates the cache entry for ['add-to-cart', productId] to 'done'.
    • Both components are notified.
    • useIsMutating now returns false.
    • Both components re-render with their updated states.

Key insight: mutationKey is the bridge that allows mutation state to escape the local component and become part of the global application state. Without an explicit key, Archibald generates one for you, but it remains unique to that specific hook instance.