clearKeyAfterMutate
Description: A config to define if the mutation is being cleared from the cache directly after it's finished or the component is unmounted.
- How To: Pass
clearKeyAfterMutate: truein theuseMutationoptions. This ensures that the mutation state (data, error, status) is deleted from the globalmutateCacheonce it completes or the component unmounts.// Correct: Clear mutation key after use for one-time actionsconst { mutate } = useMutation({clearKeyAfterMutate: true}); - Best Practice: Use
clearKeyAfterMutate: trueif you want to ensure that each mutation starts with a fresh state and doesn't leave any leftover data or errors in the cache. This is particularly useful for one-time operations or when you want to minimize the cache footprint for transient actions like "liking" a post or "sending a ping".
Deep Dive: How clearKeyAfterMutate works step by step
Example:
function LikeButton({ postId }) {
const { mutate, data } = useMutation({
mutationKey: ['like', postId],
clearKeyAfterMutate: true
});
return <button onClick={() => mutate(() => api.like(postId))}>Like</button>;
}
What happens step by step when clearKeyAfterMutate is true:
- User clicks "Like" →
mutate()is called. - Mutation executes → Result is stored in the cache.
- Mutation finishes →
datais briefly available in the component. - Cleanup timer starts →
useMutationinternally schedules a deletion. - 300ms later → Archibald deletes the entry
['like', postId]from the globalmutateCache. - Navigation occurs → Component unmounts, and the cleanup also triggers if not already done.
- The state is gone → If the component re-mounts,
dataisnullagain, even if the previous mutation was successful.
What happens step by step when clearKeyAfterMutate is false (default):
- User clicks "Like" →
mutate()is called. - Mutation executes → Result is stored in the cache.
- Mutation finishes →
datais available. - No deletion occurs → The result remains in the cache globally.
- User navigates away and back → Component re-mounts.
useMutationfinds the cached result →datais initialized with the previous result immediately.
Key insight: clearKeyAfterMutate is your tool for ensuring ephemeral mutation states. It's useful for avoiding stale UI where a button might show as "Done" or "Error" from a previous interaction that is no longer relevant.