ESC

Type to search the knowledge base.

Optimistic UI Updates

Optimistic UI updates the screen before the server confirms: apply, rollback on error, and concurrent-safe patterns.

advanced3 min read
  • react
  • optimistic-ui

Optimistic UI assumes the mutation will succeed and updates local state immediately. When the server fails, you roll back and show an error. Done well, apps feel instant; done poorly, users see ghost data and lost trust.

Docs: useOptimistic (React 19), classic manual patterns below.

Manual pattern

function LikeButton({ postId, initialCount }) {
  const [count, setCount] = useState(initialCount);
  const [error, setError] = useState(null);

  async function like() {
    setError(null);
    setCount((c) => c + 1); // optimistic
    try {
      await fetch(`/api/posts/${postId}/like`, { method: 'POST' });
    } catch (e) {
      setCount((c) => c - 1); // rollback
      setError('Could not like. Try again.');
    }
  }

  return (
    <>
      <button type="button" onClick={like}>Like ({count})</button>
      {error && <p role="alert">{error}</p>}
    </>
  );
}

useOptimistic sketch

const [optimisticLikes, addOptimistic] = useOptimistic(
  likes,
  (state, newLike) => state + 1
);

Frameworks wire this with Server Actions / transitions so the optimistic state is tied to an in-flight request.

Rules that keep you honest

  1. Idempotent-friendly mutations when users double-click.
  2. Rollback that restores previous truth, not a guessed value.
  3. Conflict policy when server returns a different final state (use server as source of truth on settle).
  4. Accessibility: announce failures; do not only change color.
  5. Lists: optimistically insert with a temporary client id, then replace with server id.

When not to be optimistic

Payments, irreversible deletes without undo, or multi-step server validation where failure is common. Prefer pending UI and disable the control.

Interview out-loud

“Optimistic UI updates local state before the server responds, then commits or rolls back. I keep the last confirmed server state for rollback, handle double-submit, and avoid optimism for irreversible money moves. React 19 useOptimistic formalizes the pattern with transitions.”

Further reading

Edge cases worth rehearsing

Interviewers and production incidents cluster around the same edges: first render versus update, empty and loading states, Strict Mode double setup, concurrent interruptions, and what happens when identity (key, route params, user id) changes mid-edit. Walk one concrete user journey end-to-end — open, edit, navigate away, come back — and say which state survives.

Prefer fixing data flow and ownership before reaching for memoization or micro-optimizations. Prefer event handlers over effects when a user action is the trigger. Prefer deriving values during render over mirroring props into state. Prefer stable list keys from business ids. Measure with the profiler when performance is the claim.

When you cite an API, mention one failure mode: abort on unmount, serializable props across server/client boundaries, focus restoration for dialogs, or cache invalidation after a mutation. Specific beats generic every time.

Edge cases worth rehearsing

Interviewers and production incidents cluster around the same edges: first render versus update, empty and loading states, Strict Mode double setup, concurrent interruptions, and what happens when identity (key, route params, user id) changes mid-edit. Walk one concrete user journey end-to-end — open, edit, navigate away, come back — and say which state survives.

Prefer fixing data flow and ownership before reaching for memoization or micro-optimizations. Prefer event handlers over effects when a user action is the trigger. Prefer deriving values during render over mirroring props into state. Prefer stable list keys from business ids. Measure with the profiler when performance is the claim.

When you cite an API, mention one failure mode: abort on unmount, serializable props across server/client boundaries, focus restoration for dialogs, or cache invalidation after a mutation. Specific beats generic every time.

Related guides