keepError
Description: Keep error in cache when transitioning between pages or when the component unmounts.
- How To: Pass
keepError: truein theuseMutationoptions. This ensures that the mutation's error state is preserved in the globalmutateCacheeven if the component is unmounted.// Correct: Keep error state during navigationconst { mutate, error } = useMutation({keepError: true,mutationKey: 'critical-update'}); - Best Practice: Use
keepError: truefor 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:
- User submits feedback → Mutation fails.
- Error is stored → The error is cached globally in
mutateCache. - User navigates away →
FeedbackFormunmounts. - Cleanup check →
useMutationseeskeepError: trueand does not clear the error on unmount. - User navigates back →
FeedbackFormre-mounts. - Error is restored →
useMutationfinds the cached error anderroris initialized with it. - User sees the error → Continuity in feedback is maintained.
What happens step by step when keepError is false (default):
- User submits feedback → Mutation fails.
- Error is stored → The error is cached globally.
- User navigates away →
FeedbackFormunmounts. - Cleanup occurs →
useMutationautomatically callsmutation.resetError()on unmount. - User navigates back →
FeedbackFormre-mounts. - Error is gone → Cache check finds no error (it was cleared on unmount).
errorisnull→ 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.