Skip to main content

keepError

Description: Keep error in cache when transitioning between pages or when the component unmounts.

  • How To: Pass keepError: true in the useMutation options. This ensures that the mutation's error state is preserved in the global mutateCache even if the component is unmounted.
    // Correct: Keep error state during navigation
    const { mutate, error } = useMutation({
    keepError: true,
    mutationKey: 'critical-update'
    });
  • Best Practice: Use keepError: true for mutations where the error provides critical feedback that the user should see even if they navigate away and then return to the page. This is particularly useful for global operations or multi-page workflows where the user might lose track of the mutation's failure.

Deep Dive: How keepError works step by step

Example:

function FeedbackForm() {
const { mutate, error } = useMutation({
mutationKey: 'feedback-submission',
keepError: true
});

return <button onClick={() => mutate(submitAction)}>Submit Feedback</button>;
}

What happens step by step when keepError is true:

  1. User submits feedback → Mutation fails.
  2. Error is stored → The error is cached globally in mutateCache.
  3. User navigates awayFeedbackForm unmounts.
  4. Cleanup checkuseMutation sees keepError: true and does not clear the error on unmount.
  5. User navigates backFeedbackForm re-mounts.
  6. Error is restoreduseMutation finds the cached error and error is initialized with it.
  7. User sees the error → Continuity in feedback is maintained.

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

  1. User submits feedback → Mutation fails.
  2. Error is stored → The error is cached globally.
  3. User navigates awayFeedbackForm unmounts.
  4. Cleanup occursuseMutation automatically calls mutation.resetError() on unmount.
  5. User navigates backFeedbackForm re-mounts.
  6. Error is gone → Cache check finds no error (it was cleared on unmount).
  7. error is null → The user has no feedback that the previous submission failed.

Key insight: keepError is the standard for persistent feedback. However, keep in mind that the error is still subject to the error TTL (default 300ms if not set or provided by client). If you want the error to persist during navigation, ensure your error TTL is long enough.