← Back to Blog
React Patterns

Mastering Optimistic UI Updates in React

📅 November 20, 2024⏱️ 8 min read

Introduction

Optimistic UI updates are a powerful pattern for creating responsive, fast-feeling applications. Instead of waiting for server confirmation before updating the UI, we immediately show the user what they expect to see, then reconcile with the server response later.

Why Optimistic Updates?

Traditional request-response flows feel slow:

  • User clicks "Like" button
  • Show loading spinner
  • Wait for server response (100-500ms)
  • Update UI

With optimistic updates:

  • User clicks "Like" button
  • Immediately show liked state
  • Send request in background
  • Reconcile if needed

This creates a perception of instant response, dramatically improving user experience.

Implementation with React Query

React Query makes optimistic updates straightforward:

import { useMutation, useQueryClient } from '@tanstack/react-query';

function LikeButton({ postId, isLiked }) {
  const queryClient = useQueryClient();
  
  const likeMutation = useMutation({
    mutationFn: (id) => api.likePost(id),
    onMutate: async (id) => {
      await queryClient.cancelQueries(['post', id]);
      const previousPost = queryClient.getQueryData(['post', id]);
      
      queryClient.setQueryData(['post', id], (old) => ({
        ...old,
        isLiked: true,
        likes: old.likes + 1
      }));
      
      return { previousPost };
    },
    onError: (err, id, context) => {
      queryClient.setQueryData(['post', id], context.previousPost);
    },
    onSettled: (id) => {
      queryClient.invalidateQueries(['post', id]);
    }
  });
  
  return (
    <button onClick={() => likeMutation.mutate(postId)}>
      {isLiked ? '❤️' : '🤍'} {likes}
    </button>
  );
}

Best Practices

1. Always Have a Rollback Strategy

Never assume the server call will succeed. Store the previous state and restore it on error.

2. Provide Visual Feedback for Pending States

Even with optimistic updates, show subtle indicators for pending operations.

3. Handle Race Conditions

Use tools like React Query's cancelQueries to prevent stale updates.

4. Be Careful with Critical Operations

Don't use optimistic updates for financial transactions, data deletion, permission changes, or anything irreversible.

Conclusion

Optimistic UI updates transform sluggish interfaces into snappy, responsive experiences. When implemented correctly with proper error handling and rollback strategies, they're one of the most impactful UX improvements you can make.

Tags

#React#UX#State Management#Performance

Written by Omobayode Festus

Senior Frontend Engineer with 5+ years of experience building scalable web applications. Passionate about React, performance optimization, and modern web architecture.