Skip to main content

useIsMutating

Description: A standalone hook (not a useMutation option) that returns true if any mutation is currently in progress (globally or for a specific key).

  • How To: Use useIsMutating to show global feedback for user actions or to monitor specific long-running mutations.
    // Global saving indicator
    function GlobalStatus() {
    const isMutating = useIsMutating();
    if (!isMutating) return null;
    return <div className="toast">Saving changes...</div>;
    }

    // Monitoring a specific mutation
    function UpdateIndicator({ productId }) {
    const isUpdating = useIsMutating(['add-to-cart', productId]);
    return <span>{isUpdating ? 'Adding to cart...' : ''}</span>;
    }
  • Best Practice: Use useIsMutating to provide visual confirmation of actions, especially for operations that don't immediately refresh the data but are critical to user feedback.

Deep Dive: How isMutating works step by step

Example:

const isMutating = useIsMutating();

What happens step by step:

  1. useMutation(...).mutate() starts
    • DataClient initiates the mutation.
    • The key for the mutation is added to the internal mutations set.
    • A 'mutate' event is published.
  2. useIsMutating() is notified
    • The hook is subscribed to the 'mutate' event globally.
    • The subscription callback is triggered.
  3. Hook re-renders
    • The hook calls client.pendingMutations().
    • It returns true because the set of active mutations is not empty.
  4. Mutation completes
    • DataClient removes the key from the mutations set.
    • A final 'mutate' event is published.
  5. Hook re-renders again
    • The hook check now returns false.

Key Specificity: Unlike useIsFetching, useIsMutating with a key currently relies on pendingMutations() (as per current implementation) which checks global state. However, it's a powerful tool for monitoring any active mutation in the system.