DEV Community

Atlas Whoff
Atlas Whoff

Posted on

Optimistic Updates in React: Instant UI With React Query

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] });
  },
});
Enter fullscreen mode Exit fullscreen mode

When NOT to Use

Avoid for destructive operations (delete account, send payment) or when server-generated values are immediately visible.

The Pattern

  1. onMutate: snapshot current state, apply optimistic update
  2. Request fires in background
  3. On success: onSettled refetches to sync
  4. On error: onError restores snapshot, onSettled refetches

Optimistic updates, React Query, and the full modern React data pattern come pre-wired in the AI SaaS Starter Kit.

Top comments (0)