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
mutationKeyin theuseMutationoptions. This key can be used to track the mutation state globally or via other hooks likeuseIsMutating.// Explicit mutation keyconst { mutate } = useMutation({mutationKey: 'update-user-profile'});// Tracking elsewhereconst isUpdating = useIsMutating('update-user-profile'); - Best Practice: Use a specific
mutationKeywhen 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:
AddToCartButtoncallsmutate()useMutationuses the provided['add-to-cart', productId]as the key.- It registers the mutation in the global
mutateCache.
CartIconis notifieduseIsMutatingis subscribed to the globalmutateCache.- It sees a mutation with key
['add-to-cart', productId]is in'fetching'status. - It returns
true, and theCartIconre-renders with a spinner.
- Mutation completes
DataClientupdates the cache entry for['add-to-cart', productId]to'done'.- Both components are notified.
useIsMutatingnow returnsfalse.- 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.