Optimistic Updates in React: Instant UI With React Query
Optimistic updates: update the UI immediately as if the server request already succeeded, then reconcile when the response arrives.
Implementation
const likeMutation = useMutation({
mutationFn: (postId: string) => api.likePost(postId),
// Step 1: Optimistically update before request fires
onMutate: async (postId) => {
await queryClient.cancelQueries({ queryKey: ['post', postId] });
const previousPost = queryClient.getQueryData(['post', postId]);
queryClient.setQueryData(['post', postId], (old: Post) => ({
...old,
likes: old.likes + 1,
likedByMe: true,
}));
return { previousPost };
},
// Step 2: Roll back on error
onError: (err, postId, context) => {
queryClient.setQueryData(['post', postId], context?.previousPost);
},
// Step 3: Always sync with server after settle
onSettled: (data, error, postId) => {
queryClient.invalidateQueries({ queryKey: ['post', postId] });
},
});
When NOT to Use
Avoid for destructive operations (delete account, send payment) or when server-generated values are immediately visible.
The Pattern
-
onMutate: snapshot current state, apply optimistic update - Request fires in background
- On success:
onSettledrefetches to sync - On error:
onErrorrestores snapshot,onSettledrefetches
Optimistic updates, React Query, and the full modern React data pattern come pre-wired in the AI SaaS Starter Kit.
Top comments (0)