Mutations and Optimistic UI Updates
0 856
๐ Mutations and Optimistic UI Updates in React
When users submit a form, like a comment or a like, they expect an instant reaction โ not a delay while the server processes it. Thatโs where mutations and optimistic UI updates come in. With TanStack Query, you can update your UI immediately while still syncing with the backend โ offering a snappy, responsive experience. โก
๐ง What Are Mutations?
Mutations are used to create, update, or delete data on the server. Unlike queries (which read data), mutations change data and may cause side effects.
import { useMutation } from '@tanstack/react-query';
const mutation = useMutation({
mutationFn: newTodo =>
fetch('/api/todos', {
method: 'POST',
body: JSON.stringify(newTodo),
}),
onSuccess: () => {
queryClient.invalidateQueries(['todos']);
}
});
- ๐
useMutationruns async logic (POST, PUT, DELETE) - โ On success, we usually invalidate queries to refetch fresh data
๐ฅ Optimistic UI Updates Explained
Optimistic updates show the **expected result** in the UI before the server confirms it. If the mutation fails, you roll back. This improves user experience, especially for actions like:
- ๐ Liking a post
- ๐๏ธ Deleting an item
- ๐ค Submitting a comment
โ Basic Optimistic Update Example
Let's say weโre deleting a todo from the list:
import { useMutation, useQueryClient } from '@tanstack/react-query';
function useDeleteTodo() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: (id) => fetch(`/api/todo/${id}`, { method: 'DELETE' }),
onMutate: async (id) => {
await queryClient.cancelQueries(['todos']);
const previousTodos = queryClient.getQueryData(['todos']);
queryClient.setQueryData(['todos'], old =>
old.filter(todo => todo.id !== id)
);
return { previousTodos };
},
onError: (err, id, context) => {
queryClient.setQueryData(['todos'], context.previousTodos);
},
onSettled: () => {
queryClient.invalidateQueries(['todos']);
}
});
}
๐ Breakdown of Optimistic Flow
- โ onMutate: Called before mutation runs โ stores the current data and shows the optimistic UI
- โ onError: Rolls back to previous state if mutation fails
- โ onSettled: Always called โ revalidates data from server
โ๏ธ Optimistic Add Example (Add Comment)
const addCommentMutation = useMutation({
mutationFn: newComment =>
fetch('/api/comments', {
method: 'POST',
body: JSON.stringify(newComment)
}).then(res => res.json()),
onMutate: async (newComment) => {
await queryClient.cancelQueries(['comments']);
const previous = queryClient.getQueryData(['comments']);
queryClient.setQueryData(['comments'], old => [
...old,
{ id: Date.now(), ...newComment, optimistic: true }
]);
return { previous };
},
onError: (err, newComment, context) => {
queryClient.setQueryData(['comments'], context.previous);
},
onSettled: () => {
queryClient.invalidateQueries(['comments']);
}
});
๐ฏ This makes it feel like the comment is instantly added โ even though the network request may take time.
๐ง Considerations with Optimistic UI
- ๐ก๏ธ Always store
previousDatafor rollback - ๐ซ Donโt show destructive UI changes unless you handle rollback properly
- ๐ Gracefully handle server errors to maintain trust
๐ Summary
- ๐ useMutation lets you update server data
- โก Optimistic updates improve user experience by updating UI instantly
- ๐งฏ Include
onErrorandonMutatefor rollback - โป๏ธ Re-fetch with
invalidateQueriesto stay in sync
๐ Final Thoughts
Mutations and optimistic UI updates make your apps feel faster and more interactive โ just like native apps. With React 19 and TanStack Query, implementing them is not only easy but incredibly powerful. Your users get a seamless experience, and your code stays clean and maintainable. ๐ฌโ
If youโre passionate about building a successful blogging website, check out this helpful guide at Coding Tag โ How to Start a Successful Blog. It offers practical steps and expert tips to kickstart your blogging journey!
For dedicated UPSC exam preparation, we highly recommend visiting www.iasmania.com. It offers well-structured resources, current affairs, and subject-wise notes tailored specifically for aspirants. Start your journey today!
Share:




Comments
Waiting for your comments