Mutation Callbacks: onSuccess, onError, onSettled
What you'll learn: How to execute side effects like navigation, toasts, or cleanup automatically when your mutations complete, fail, or finish—regardless of outcome.
The Core Idea
When you use useMutation to modify server data, you often need to do something after the mutation finishes—show a success message, redirect the user, or log an error. TanStack Query provides three lifecycle callbacks that run at specific moments: onSuccess (mutation succeeded), onError (mutation failed), and onSettled (mutation finished, either way).
Think of these callbacks like event handlers for your mutation's lifecycle—similar to how you'd use onClick for user interactions, but triggered by mutation outcomes instead.
Why You Need Them
After creating a new post, you might want to:
- Show a toast notification ("Post created!")
- Navigate to the new post's page
- Close a modal
- Clear a form
- Track analytics
These callbacks let you coordinate these side effects cleanly without manual promise handling.
How They Work
const mutation = useMutation({
mutationFn: createPost,
onSuccess: (data, variables, context) => {
toast.success('Post created!');
navigate(`/posts/${data.id}`);
},
onError: (error, variables, context) => {
toast.error(`Failed: ${error.message}`);
},
onSettled: (data, error, variables, context) => {
// Runs regardless of success/error
setIsModalOpen(false);
}
});
Parameters: Each callback receives the mutation result (data or error), the variables you passed to mutate(), and context (for advanced patterns).
Execution order: onSuccess OR onError runs first, then onSettled always runs last—like a finally block.
Key Takeaway: Use onSuccess for happy-path actions, onError for failure handling, and onSettled for cleanup that must happen regardless of outcome—making your mutation side effects predictable and centralized.