Mutation Context: Passing Data Through Callbacks
What you'll learn: How to pass data from onMutate through your mutation lifecycle callbacks for rollback and cleanup logic.
The Problem: Sharing Data Across Callbacks
When performing optimistic updates, you often need to store information in onMutate (like the previous cache state) and use it later in onError or onSettled. But these callbacks run at different times—how do you pass data between them?
The Context Flow
TanStack Query provides a context mechanism specifically for this. Whatever you return from onMutate becomes available as a parameter in both onError and onSettled:
const mutation = useMutation({
mutationFn: updateTodo,
onMutate: async (newData) => {
// Save previous state
const previousTodos = queryClient.getQueryData(['todos']);
// Return it as context
return { previousTodos };
},
onError: (error, variables, context) => {
// context contains what onMutate returned
if (context?.previousTodos) {
queryClient.setQueryData(['todos'], context.previousTodos);
}
},
onSettled: (data, error, variables, context) => {
// context is available here too for cleanup
console.log('Original data:', context?.previousTodos);
}
});
The Analogy
Think of context like a relay baton in a race. onMutate creates the baton (the previous state), then hands it to onError and onSettled so they can complete the race with all the information they need.
Why It Matters
Without context, you'd need global variables or additional state to track rollback data—messy and error-prone. Context keeps your mutation logic self-contained and predictable.
Key Takeaway: Return data from onMutate to create context that flows through onError and onSettled, enabling clean rollback and cleanup logic without external state.