Optimistic versus confirmed updates
| Approach | Benefits | Limitations | Typical use |
|---|---|---|---|
| Optimistic | Immediate visible change | Reconciliation and divergence | Favorites, simple preferences |
| Confirmed | No unconfirmed business result | Waiting for completion | Payments, reservations, permissions |
| Hybrid | Immediate pending feedback without claiming success | Explicit status model | Message 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
| Strategy | When to use | Limitation |
|---|---|---|
| One active write per entity | Simple settings and toggles | Restricts subsequent interaction |
| Per-entity queue | Order matters | Does not coordinate other tabs or devices |
| Overlays and intent replay | Independent fields or entities | Needs ordering and conflict rules |
| Versioned conditional writes | Multiple editors | Requires 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
| Outcome | Client behavior |
|---|---|
| Confirmed write | Adopt canonical snapshot and remove overlay |
| Definitive rejection | Remove matching overlay, preserve newer data, explain reason |
| Timeout, disconnect, ambiguous 5xx | Mark unknown; resolve operation status or safely retry with same key |
| Version conflict | Refresh 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
| Solution | Mechanism | Choose when | Still design |
|---|---|---|---|
| React useOptimistic | Action overlay | Local view, React 19+ | Durable state, errors, write ordering |
| TanStack Query | variables, onMutate, setQueryData, invalidation | Shared API data | Conflicts, related keys |
| SWR | optimisticData, rollbackOnError, mutate | Existing SWR app | Rollback rules and multi-key consistency |
| Apollo Client | optimisticResponse, normalized cache | GraphQL | Entity identity, lists, error policy |
| RTK Query | updateQueryData, undo, tag invalidation | Existing Redux Toolkit | Overlapping 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
| Scenario | Expected result |
|---|---|
| Slow response | Immediate feedback, still pending |
| A rejected after B succeeds | B is not erased |
| Old refetch after new write | Confirmed revision never regresses |
| Response lost after commit | No false failure claim; resolve outcome |
| Retry with same key | Server does not duplicate effect |
| Two tabs or devices | Server detects conflicts |
| Offline restart or account change | Outbox recovered according to policy; account isolation |
| Keyboard and screen reader | Status 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.
