Skip to content

Search

Articles, tools, solutions and knowledge base guides

Start typing to search across articles, tools and apps.

Optimistic UI: Optimistic Updates, State Synchronization and Error Handling

A favorite button need not wait for an API response, but its displayed value is not proof of persistence. Optimistic UI improves perceived responsiveness when the application distinguishes prediction from confirmed data. This guide explains how to choose an update strategy, design the server contract and prevent lost updates.

Published Written by Reading time 12 min read
On this page Contents: quick navigation between sections

Optimistic versus confirmed updates

ApproachBenefitsLimitationsTypical use
OptimisticImmediate visible changeReconciliation and divergenceFavorites, simple preferences
ConfirmedNo unconfirmed business resultWaiting for completionPayments, reservations, permissions
HybridImmediate pending feedback without claiming successExplicit status modelMessage sending, order processing

An optimistic update displays the predicted mutation result before the request finishes. A pessimistic update retains the previous business state until an authoritative result arrives. Both can acknowledge the interaction immediately. Optimistic UI does not reduce server processing time or guarantee better INP; it shortens time to visible feedback if rendering remains fast. [1][2]

Never label a payment, ticket purchase or deletion as completed before authoritative confirmation. Show progress, a local draft or a pending submission instead. Choose according to reversibility, conflict probability, consequences of a wrong prediction and ability to explain uncertainty.

Confirmed data and pending intents

Related reading: React Rendering, Reconciliation and State.

Keep the authoritative snapshot separate from temporary operations. Derive the view by applying active intents to the latest known snapshot. On acceptance adopt the canonical result, respecting versions; on definitive rejection remove only the corresponding intent. Do not restore an entire cache unconditionally. [1][2][5]

An operation ID correlates requests and responses; an entity revision orders server snapshots. These are distinct. A read started before a write can complete after it. Response arrival order does not establish freshness. Discard older snapshots if the backend provides monotonic revisions. An ETag is an opaque validator, not a sortable counter. [7]

Concurrent mutations and rollback

StrategyWhen to useLimitation
One active write per entitySimple settings and togglesRestricts subsequent interaction
Per-entity queueOrder mattersDoes not coordinate other tabs or devices
Overlays and intent replayIndependent fields or entitiesNeeds ordering and conflict rules
Versioned conditional writesMultiple editorsRequires a backend contract

Suppose A renames X to Y, then B changes Y to Z. If B succeeds and A fails, restoring X from A's snapshot may erase B. If the server executes A after B, ignoring the old response does not undo the actual write. Solve both client and server ordering problems.

Shared views need consistent entity identity, including filtered lists, pagination and counts. Cancelling reads can protect an overlay but cannot undo a committed mutation. Revalidate relevant queries after related writes settle or adopt a complete canonical result. Premature invalidation may briefly display stale data. [2][3][6]

HTTP contracts, idempotency and uncertain outcomes

OutcomeClient behavior
Confirmed writeAdopt canonical snapshot and remove overlay
Definitive rejectionRemove matching overlay, preserve newer data, explain reason
Timeout, disconnect, ambiguous 5xxMark unknown; resolve operation status or safely retry with same key
Version conflictRefresh and resolve conflict before writing again

Prefer setting selected=true over toggle. Idempotency concerns the intended effect of repeated requests, not identical responses. PUT is idempotent by HTTP semantics but does not automatically deduplicate side effects. For POST, design an idempotency key: atomically retain the outcome, bind the key to the user and request, recognize retries and reject reuse with a different payload. Define retention. [7]

A strong ETag with If-Match or an atomic revision precondition prevents lost updates. A failed If-Match normally yields 412; 409 can represent a domain conflict. Retrieve current data and let the user decide whether to reapply an intent. Never silently retry with a new version if that could overwrite someone else's change. [7]

A missing response does not prove the write failed. A plain GET may not establish whether a specific operation committed or is still running. Use a reliable operation-status or retry contract that returns the terminal result. The backend always enforces authorization, validation and business rules.

Example favorite contract: PUT /api/favorites/42 carries the target value and operation ID (for example an agreed header), with If-Match as a possible version precondition. The backend returns the confirmed value and revision. On retry, authenticate and verify request identity and payload, then recognize a recorded terminal result before evaluating the current revision. Otherwise the original successful write may cause an apparent conflict on retry. This is a proposed application contract, not an automatic HTTP guarantee. [7]

Choosing a modern frontend mechanism

SolutionMechanismChoose whenStill design
React useOptimisticAction overlayLocal view, React 19+Durable state, errors, write ordering
TanStack Queryvariables, onMutate, setQueryData, invalidationShared API dataConflicts, related keys
SWRoptimisticData, rollbackOnError, mutateExisting SWR appRollback rules and multi-key consistency
Apollo ClientoptimisticResponse, normalized cacheGraphQLEntity identity, lists, error policy
RTK QueryupdateQueryData, undo, tag invalidationExisting Redux ToolkitOverlapping patches and invalidation

Related reading: React Hooks: useState, useEffect and More.

React 19 useOptimistic holds temporary state during an Action using a pure updater; when the base changes the reducer is reapplied. It does not replace a server cache, request deduplication or revision control. TanStack Query v5 supports rendering pending variables or modifying its cache. Mutation scope serializes execution within that client, not across the server. [1][2][8]

Do not replace a library solely to obtain optimistic updates. Start with a local overlay for one view; use the existing server-state cache for multiple consumers. Complex conflicts require a synchronization protocol independent of components. Apollo removes the temporary layer but new entity identity and list membership still matter. Overlapping RTK Query patches may require refetching rather than undoing old patches. [4][5]

In React, call the useOptimistic setter within an Action or startTransition and update the base on success. TanStack Query variables-only rendering does not change the cache; onMutate may cancel related reads, apply the update and reconcile relevant keys after settlement. Returning the invalidation Promise keeps the mutation pending until refresh completes. An onMutate snapshot is not inherently safe under overlapping writes. Configure SWR rollbackOnError according to whether the error proves rejection. [1][2][3][6]

TypeScript example: favoriting an item

src/favorite.ts

export interface Snapshot {
  readonly selected: boolean;
  readonly revision: number;
}

export interface Operation {
  readonly id: string;
  readonly selected: boolean;
  readonly expectedRevision: number;
  readonly status: "pending" | "unknown";
}

export interface State {
  readonly confirmed: Snapshot;
  readonly operation: Operation | null;
  readonly notice: "none" | "rejected" | "unknown";
}

export type Event =
  | { type: "begin"; id: string; selected: boolean }
  | { type: "snapshot"; snapshot: Snapshot }
  | { type: "accepted"; id: string; snapshot: Snapshot }
  | { type: "rejected"; id: string; snapshot: Snapshot }
  | { type: "unknown"; id: string };

function newest(current: Snapshot, incoming: Snapshot): Snapshot {
  if (incoming.revision <= current.revision) {
    return current;
  }

  return incoming;
}

export function visibleSelection(state: State): boolean {
  return state.operation?.selected ?? state.confirmed.selected;
}

export function reduce(state: State, event: Event): State {
  switch (event.type) {
    case "begin": {
      if (state.operation !== null) {
        return state;
      }

      if (event.selected === state.confirmed.selected) {
        return state;
      }

      return {
        ...state,
        operation: {
          id: event.id,
          selected: event.selected,
          expectedRevision: state.confirmed.revision,
          status: "pending",
        },
        notice: "none",
      };
    }

    case "snapshot":
      return {
        ...state,
        confirmed: newest(state.confirmed, event.snapshot),
      };

    case "unknown": {
      if (state.operation?.id !== event.id) {
        return state;
      }

      return {
        ...state,
        operation: { ...state.operation, status: "unknown" },
        notice: "unknown",
      };
    }

    case "accepted":
    case "rejected": {
      if (state.operation?.id !== event.id) {
        return state;
      }

      return {
        confirmed: newest(state.confirmed, event.snapshot),
        operation: null,
        notice: event.type === "rejected" ? "rejected" : "none",
      };
    }
  }
}

This reducer handles one entity and one active write. It separates server snapshots from the visible value, ignores older revisions and unrelated responses, and blocks new writes to that entity after an uncertain result until resolution. It is deliberately not an offline queue or complete HTTP client.

The adapter must accept begin atomically in the local store and send only when a new operation was created, with a unique ID and expectedRevision. Validate incoming snapshots and terminal responses at the API boundary (safe integer revision, boolean, matching entity and operation identity). Revisions are monotonic and equal revisions represent identical content. Do not invent revisions on the client. HTTP 202 alone is not accepted in this model: it indicates acceptance for processing, not completion. [7]

Render visibleSelection and use operation.status and notice for feedback. Emit unknown after ambiguous failure, and accepted or rejected only with a definitive server outcome and snapshot. A delayed terminal result cannot replace a newer snapshot. The backend contract must guarantee finality; without it uncertainty must remain visible.

Offline-first, creation and accessible UX

Related reading: Service Workers: Caching, Offline and Updates.

Optimistic UI is not offline-first. A persistent outbox (for example IndexedDB) needs operation IDs, payloads, versions, ordering, statuses, bounded backoff, account isolation and fresh authorization. Browser storage may be evicted. Background Sync has limited availability, so support replay while the app is open. [8][9][10]

For creation use a stable local identity and explicitly map it to the server ID when server-generated. Preserve rendering keys during reconciliation, rewrite dependent operations and avoid duplicate rows on refetch. Do not invent server-calculated prices or permissions.

Display saving, awaiting synchronization, outcome unknown and clear rejection messages. Avoid relying on color alone or moving focus unnecessarily. Expose status changes to assistive technologies, for example role=status for polite updates. Offer retry or conflict resolution when action is required. [11]

Testing, measurements and rollout

ScenarioExpected result
Slow responseImmediate feedback, still pending
A rejected after B succeedsB is not erased
Old refetch after new writeConfirmed revision never regresses
Response lost after commitNo false failure claim; resolve outcome
Retry with same keyServer does not duplicate effect
Two tabs or devicesServer detects conflicts
Offline restart or account changeOutbox recovered according to policy; account isolation
Keyboard and screen readerStatus is understandable without moving focus

Reducer unit tests cover state; contract tests must establish backend versioning and idempotency. Integration tests should control response ordering, E2E should exercise actual network errors and interaction. Measure time to feedback separately from time to confirmation, rejection and unknown-outcome rates, conflicts, retries and reconciliation duration. Use p50/p95 instead of averages alone. INP does not measure completion of a network mutation. [12]

Roll out gradually: select a reversible operation, establish the contract and error scenarios, compare metrics with confirmed updates, then expand. Do not add global rollback or automatic retry without analyzing operation semantics. If consistency or trust deteriorates, return to confirmed updates.

Start with a reversible operation and an explicit synchronization contract. Expand only after validating consistency, accessibility and user metrics. For consequential operations show a pending state rather than predicted success.

Optimistic UI React State Management TanStack Query HTTP Idempotency Offline-first TypeScript

Frequently asked questions

Does Optimistic UI speed up the backend?

No. It changes when the predicted result appears, not when the write commits.

Is rollback on every error correct?

No. Resolve ambiguous outcomes and remove only the matching overlay after definitive rejection.

Does useOptimistic replace TanStack Query?

No. One handles temporary UI state, the other the server data lifecycle. They can coexist, but do not apply the same change twice. [1][2]

Does idempotency resolve write conflicts?

No. It protects the intended effect of retries; distinct writes need their own conflict policy. [7]

Should every offline app use Optimistic UI?

No. Durable queues, security and reconciliation are separate requirements.

When should the interface wait?

When business rules are unpredictable or a false success has serious consequences, such as payments.

Sources and references

  1. React: useOptimistic↩1↩2↩3↩4↩5↩6
  2. TanStack Query: Optimistic Updates↩1↩2↩3↩4↩5↩6↩7
  3. SWR: Mutation & Revalidation↩1↩2
  4. Apollo Client: Optimistic mutation results↩
  5. RTK Query: Manual Cache Updates↩1↩2
  6. TanStack Query: Invalidations from Mutations↩1↩2
  7. RFC 9110: HTTP Semantics (sections 9.2.2, 13.1.1, 15.3.3, 15.5.10, 15.5.13)↩1↩2↩3↩4↩5↩6↩7
  8. TanStack Query: Mutations↩1↩2
  9. MDN: Background Synchronization API↩
  10. MDN: IndexedDB key characteristics and basic terminology↩
  11. W3C WAI: Understanding WCAG 2.2 SC 4.1.3, Status Messages↩
  12. web.dev: Understanding INP↩

Was this helpful?

Get new articles by email

One short email per new Learning article. No spam, unsubscribe in one click.

We only use your email to send new articles. No third-party sharing.

Back to Learning