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
useIsMutatingto show global feedback for user actions or to monitor specific long-running mutations.// Global saving indicatorfunction GlobalStatus() {const isMutating = useIsMutating();if (!isMutating) return null;return <div className="toast">Saving changes...</div>;}// Monitoring a specific mutationfunction UpdateIndicator({ productId }) {const isUpdating = useIsMutating(['add-to-cart', productId]);return <span>{isUpdating ? 'Adding to cart...' : ''}</span>;} - Best Practice: Use
useIsMutatingto 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:
useMutation(...).mutate()startsDataClientinitiates the mutation.- The key for the mutation is added to the internal
mutationsset. - A
'mutate'event is published.
useIsMutating()is notified- The hook is subscribed to the
'mutate'event globally. - The subscription callback is triggered.
- The hook is subscribed to the
- Hook re-renders
- The hook calls
client.pendingMutations(). - It returns
truebecause the set of active mutations is not empty.
- The hook calls
- Mutation completes
DataClientremoves the key from themutationsset.- A final
'mutate'event is published.
- Hook re-renders again
- The hook check now returns
false.
- The hook check now returns
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.