Mutations and Optimistic UI Updates
×


Mutations and Optimistic UI Updates

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']);
  }
});
  • ๐Ÿ” useMutation runs 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 previousData for 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 onError and onMutate for rollback
  • โ™ป๏ธ Re-fetch with invalidateQueries to 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!



Best WordPress Hosting


Share:


Discount Coupons

Unlimited Video Generation

Best Platform to generate videos

Search and buy from Namecheap

Secure Domain for a Minimum Price



Leave a Reply


Comments
    Waiting for your comments

Coding Tag WhatsApp Chat