React Tutorial 0/120 lessons ~6 min read Lesson 71

    Optimistic UI

    Optimistic UI covers predicting success in the UI with React 19 useOptimistic and TanStack Query, rollback data, concurrency hazards, poor candidates, and reconciling after mutations.

    Course progress0%
    Focus
    12 guided sections
    Practice signal
    Examples included
    Career prep
    Interview Q&A included

    Course: React — State Management Lesson: 11

    Learning objectives

    Explain optimistic updates, implement a basic optimistic workflow, roll back failed mutations, and recognize concurrency and consistency challenges.

    What is optimistic UI?

    Optimistic UI updates the interface immediately after a user action, before the server confirms the change. The application assumes success temporarily to make the interaction feel responsive.

    text
    User action
    |
    v
    Update visible UI immediately
    |
    v
    Send mutation to server
    / \
    / \
    success failure
    | |
    keep rollback or reconcile

    Example: mark a task complete

    The user clicks Complete. The task appears completed immediately. The application sends the mutation. If the server rejects it, the UI restores the previous value and explains the failure.

    Two common approaches: React 19's built-in useOptimistic, and cache-level optimism with TanStack Query. Both are valid; pick based on whether React state or a shared query cache owns the list.

    Approach A: React 19 useOptimistic

    Use when the optimistic value lives in React state (or props that flow into a Client Component). React shows the optimistic value during the transition, then reverts to the confirmed state when the update finishes or fails.

    tsx
    import { useOptimistic, useState, startTransition } from "react";
    type Task = { id: string; title: string; completed: boolean };
    function TaskRow({
    task,
    onComplete,
    }: {
    task: Task;
    onComplete: (id: string) => Promise<Task>;
    }) {
    const [confirmed, setConfirmed] = useState(task);
    const [optimisticTask, setOptimisticTask] = useOptimistic(
    confirmed,
    (current, nextCompleted: boolean) => ({ ...current, completed: nextCompleted }),
    );
    function handleComplete() {
    startTransition(async () => {
    setOptimisticTask(true);
    try {
    const saved = await onComplete(task.id);
    setConfirmed(saved);
    } catch {
    // Optimistic value discarded when the transition ends without updating confirmed.
    setConfirmed(task);
    }
    });
    }
    return (
    <li>
    <span>{optimisticTask.title}</span>
    <button type="button" onClick={handleComplete} disabled={optimisticTask.completed}>
    {optimisticTask.completed ? "Done" : "Complete"}
    </button>
    </li>
    );
    }

    Label: React 19 API — no query library required. Pair with Actions / startTransition for pending UX. Prefer this for local UI; prefer TanStack Query when many screens share one server cache.

    Approach B: TanStack Query optimistic mutation

    javascript
    const mutation = useMutation({
    mutationFn: updateTask,
    onMutate: async (updatedTask) => {
    await queryClient.cancelQueries({ queryKey: ["tasks"] });
    const previousTasks = queryClient.getQueryData(["tasks"]);
    queryClient.setQueryData(["tasks"], current =>
    current?.map(task =>
    task.id === updatedTask.id
    ? { ...task, completed: updatedTask.completed }
    : task
    )
    );
    return { previousTasks };
    },
    onError: (_error, _updatedTask, context) => {
    queryClient.setQueryData(["tasks"], context.previousTasks);
    },
    onSettled: () => {
    queryClient.invalidateQueries({ queryKey: ["tasks"] });
    }
    });

    Label: TanStack Query pattern — snapshot the cache, apply an optimistic update, roll back on error, invalidate to reconcile. Production code should account for absent cache data, concurrent mutations, and the exact API response contract.

    Concurrency concerns

    If two updates happen before the first completes, restoring an old whole-cache snapshot can accidentally erase a newer successful update. Consider per-entity updates, mutation identifiers, version numbers, or server reconciliation for high-concurrency workflows.

    When optimistic UI is appropriate

    Good candidates include liking a post, toggling a preference, marking a task complete, or reordering a personal list. Be more cautious with payments, financial transfers, inventory reservations, and actions with irreversible consequences.

    User feedback

    If a mutation fails, clearly communicate that the change was not saved. Avoid silently rolling back a visible action. Provide retry or correction options when appropriate.

    Common mistakes

    • Optimistically updating without a rollback plan.
    • Restoring stale snapshots during concurrent mutations.
    • Using optimistic UI for high-risk operations without careful server design.
    • Forgetting to reconcile with the authoritative server response.
    • Allowing duplicate submissions.

    Best practices

    Snapshot the relevant previous state, cancel conflicting refetches, apply a minimal optimistic change, roll back carefully, and reconcile with the server. Use optimistic behavior only when the user benefit outweighs consistency risk.

    Interview questions & answers

    Interview preparation

    5 questions grouped by difficulty — expand any card for a model answer and follow-up probe.

    Beginner

    2
    1. 1What is optimistic UI?
      Beginner

      Model answer

      Updating the UI as if a mutation succeeded before the server confirms, then reconciling or rolling back.

    2. 2Which operations are poor candidates for optimistic updates?
      Beginner

      Model answer

      High-risk or hard-to-reverse operations such as payments, irreversible deletes, or flows with complex server-side validation.

    Intermediate

    2
    1. 3What information is needed for rollback?
      Intermediate

      Model answer

      Enough prior cache/UI snapshot to restore the previous state if the mutation fails.

    2. 4Why should the cache be reconciled after a mutation?
      Intermediate

      Model answer

      The server is authoritative; reconciling replaces temporary predictions with confirmed data and corrects drift.

    Advanced

    1
    1. 5Why can concurrent mutations make rollback difficult?
      Advanced

      Model answer

      Overlapping updates can invalidate snapshots; rolling back one mutation may undo another mutation's intermediate result.

    Practice

    Implement optimistic task completion and task reordering. Simulate a server failure and two overlapping updates to test rollback correctness.

    Ready to mark this lesson complete?Track your journey across the entire course.