Mutations and Optimistic UI Updates
×


Mutations and Optimistic UI Updates

993

🔄 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