error
Description: Defines how long a mutation error is kept in the cache.
- How To: Pass
error(in milliseconds) in theuseMutationoptions. This determines how long theerrorstate persists before it is automatically cleared from the globalmutateCache.// Correct: Keep error state for 10 secondsconst { mutate, error } = useMutation({error: 10 * 1000,mutationKey: 'login-attempt'});const onLogin = () => {mutate(() => api.login(credentials));}; - Best Practice: Use shorter durations for transient errors that should clear quickly, and longer ones for critical errors that need to be acknowledged by the user. If you're using a global error notification system that observes the
mutateCache, theerrorTTL will control how long the error is visible to that system.// Avoid this: Setting a very high error TTL without a reset mechanismconst { mutate, error, resetError } = useMutation({error: 60 * 60 * 1000 // 1 hour!});// The user will see this error for an hour unless you call resetError()!
Deep Dive: How error works step by step
Example:
function SubmissionForm() {
const { mutate, error } = useMutation({
mutationKey: 'form-submission',
error: 5000 // 5 seconds
});
return <button onClick={() => mutate(submitAction)}>Submit</button>;
}
What happens step by step with the timeline:
-
t=0s: User clicks submit
- Mutation executes and fails.
- Error is stored in
mutateCachewith key'form-submission'. - Error expires at:
t=0s + 5s = t=5s.
-
t=2s: Error is displayed
- Component renders with the
errorobject. - User sees the error message.
- Component renders with the
-
t=6s: Error expires
DataClientoruseMutationhook detects the expired error.- Error is cleared from the cache entry.
- Component re-renders, and
erroris nownull.
-
t=10s: User navigates away and back
- Component re-mounts.
- Cache is checked for
'form-submission'. - No error found as it has already been cleared.
Key insight: The error TTL is essential for preventing stale errors from lingering in the UI. Combined with keepError: true, it ensures that critical errors survive navigation but still clear automatically after a reasonable period.