Full answer
Waiting for the server before showing a change feels slow. An optimistic update shows the expected result at once and corrects it if the request fails. It suits low-risk actions that nearly always succeed: toggles, likes, reordering. Avoid it for payments or operations with complex server rules.
TanStack Query provides the lifecycle in useMutation:
onMutate(variables)runs before the request. Callawait queryClient.cancelQueries({ queryKey })so an in-flight refetch cannot overwrite the optimistic value. Readprevious = queryClient.getQueryData(queryKey). Write the new value withqueryClient.setQueryData(queryKey, updater)and return{ previous }.onError(error, variables, context)restorescontext.previouswithsetQueryData.onSettledcallsqueryClient.invalidateQueries({ queryKey }), so the cache is refreshed from the server whether the request succeeded or failed. This corrects any difference between the guess and the real result.
Details that matter. Updaters must be immutable: return a new array or object. When several mutations can overlap, rolling back a snapshot may undo a later successful change, so invalidate and refetch after the last one finishes or use mutation keys and isMutating to skip invalidation until the queue is empty. A simpler variant (since v5) renders the pending variables directly from useMutation's variables while isPending is true, without touching the cache, which avoids rollback code entirely and works well for a single list. Show errors with a toast so users know the change did not stick.
Alternatives: React 19 useOptimistic gives local optimistic state tied to a transition or form action and reverts automatically when the action ends. For server-driven frameworks that is often enough. For shared cache state across components, the query cache approach is better.
Test the failure path, because rollback code is rarely exercised in manual testing.
The example toggles a lesson as done. The first request fails on purpose.
import { QueryClient, QueryClientProvider, useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
let serverDone = false;
let calls = 0;
const fetchLesson = () => new Promise((resolve) => setTimeout(() => resolve({ done: serverDone }), 10));
const saveLesson = (done) =>
new Promise((resolve, reject) =>
setTimeout(() => {
calls += 1;
if (calls === 1) reject(new Error('Network error'));
else {
serverDone = done;
resolve({ done });
}
}, 80)
);
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
function Lesson() {
const client = useQueryClient();
const { data } = useQuery({ queryKey: ['lesson'], queryFn: fetchLesson });
const mutation = useMutation({
mutationFn: saveLesson,
onMutate: async (done) => {
await client.cancelQueries({ queryKey: ['lesson'] });
const previous = client.getQueryData(['lesson']);
client.setQueryData(['lesson'], { done });
return { previous };
},
onError: (_error, _done, context) => {
client.setQueryData(['lesson'], context.previous);
},
onSettled: () => client.invalidateQueries({ queryKey: ['lesson'] }),
});
if (!data) return <p>Loading...</p>;
return (
<div>
<p>{data.done ? 'Lesson done' : 'Lesson not done'}</p>
<button onClick={() => mutation.mutate(!data.done)}>Toggle</button>
</div>
);
}
export default function App() {
return (
<QueryClientProvider client={queryClient}>
<Lesson />
</QueryClientProvider>
);
}The fake server rejects the first request and accepts the next ones. The check clicked Toggle, read the text before the server answered, and again after the failure, and then repeated with a request that succeeds. Output of the run: loaded: Lesson not done right after clicking (server not answered yet, request will fail): Lesson done after the failed request: Lesson not done second click, optimistic: Lesson done after the successful request: Lesson done
Key points
- onMutate cancels queries, snapshots the cache, writes the optimistic value and returns context.
- onError restores the snapshot. onSettled invalidates to sync with the server.
- Updaters must be immutable, and overlapping mutations need care.
- The variables-based variant renders pending data without cache writes.
- useOptimistic is the React-level alternative for local or form-driven cases.
Common mistakes
- Forgetting cancelQueries, so a refetch overwrites the optimistic value.
- Mutating cached data instead of returning a new value.
- Skipping onSettled invalidation, leaving the cache out of sync.
- Using optimistic updates for actions that often fail or have side effects.
- Not testing the rollback path.
Follow-ups
- How do you handle two quick mutations that overlap?
- When is useOptimistic a better choice than the query cache?
- How does the variables-based approach avoid rollback code?
Tips
- Walk through the three callbacks in order.
- Mention overlapping mutations. It is the senior-level caveat.
- Say you test the failure path.