Skip to main content

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: true in the useMutation options. This ensures that the mutation state (data, error, status) is deleted from the global mutateCache once it completes or the component unmounts.
    // Correct: Clear mutation key after use for one-time actions
    const { mutate } = useMutation({
    clearKeyAfterMutate: true
    });
  • Best Practice: Use clearKeyAfterMutate: true if 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:

  1. User clicks "Like"mutate() is called.
  2. Mutation executes → Result is stored in the cache.
  3. Mutation finishesdata is briefly available in the component.
  4. Cleanup timer startsuseMutation internally schedules a deletion.
  5. 300ms later → Archibald deletes the entry ['like', postId] from the global mutateCache.
  6. Navigation occurs → Component unmounts, and the cleanup also triggers if not already done.
  7. The state is gone → If the component re-mounts, data is null again, even if the previous mutation was successful.

What happens step by step when clearKeyAfterMutate is false (default):

  1. User clicks "Like"mutate() is called.
  2. Mutation executes → Result is stored in the cache.
  3. Mutation finishesdata is available.
  4. No deletion occurs → The result remains in the cache globally.
  5. User navigates away and back → Component re-mounts.
  6. useMutation finds the cached resultdata is 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.