Optimistic React updates after failure
Optimistic UI should display a proposed change while preserving the server-confirmed state underneath. Roll back a confirmed rejection, reconcile an unknown outcome, and identify each mutation so a late failure cannot erase a newer edit.
Inside this article 4 sections +
An optimistic update is a prediction about a server operation. It can make an interface feel immediate, but the application still needs to learn whether the prediction became true. Treating every network error as a rejection creates a subtle failure: the screen rolls back a change that the server already accepted.
Use a shared project board as an example. A user moves a task from Planned to Active. The browser shows the move immediately, while the request is in flight. Another user may edit the same task, the response may arrive late, or the connection may disappear after the server commits. Each situation needs a different response.
Keep confirmed state separate from pending intent
Maintain the last server-confirmed task state as the base and represent the pending move as an operation with its own identity. Render the optimistic view by applying that intent to the base. React's useOptimistic supports temporary optimistic state during Actions, but the hook does not define your server's mutation identity, conflict policy, or recovery protocol.
The optimistic transformation should be pure and describe the intended change. For a move, it might say that task T should appear in Active while operation M is pending. Avoid capturing and restoring an entire board snapshot as the only recovery strategy. That snapshot can become stale as unrelated tasks change or newer operations complete.
| Server knowledge | Visible state | Recovery action |
|---|---|---|
| Accepted with canonical revision | Saved move | Update the base and remove the pending intent |
| Rejected by a confirmed rule | Previous valid position plus explanation | Remove only this intent and retain editable user input |
| No authoritative outcome | Move marked as awaiting confirmation | Query or repeat the same operation identity |
This dependency-free JavaScript fixture models one task’s stage. A confirmed rejection removes its own pending operation, then the screen is derived again. It avoids restoring an entire old screen snapshot over a later user action.
import assert from 'node:assert/strict';
function stageForView(confirmedStage, pendingMoves) {
return pendingMoves.reduce((stage, move) => move.to, confirmedStage);
}
const base = 'Backlog';
const pending = [
{ id: 'move-1', to: 'Active' },
{ id: 'move-2', to: 'Review' }
];
const afterFirstRejected = pending.filter(move => move.id !== 'move-1');
assert.equal(stageForView(base, afterFirstRejected), 'Review');
assert.equal(stageForView(base, []), 'Backlog');
This projection does not authorize the second move or implement server response ordering. If Review requires an accepted Active transition, the product must revalidate that dependent intent after rejection. Update the confirmed base only from authoritative, revision-aware results; use reconciliation for timeouts instead of treating them as confirmed rejection.
Roll back a rejection without losing user work
A clear permission error or validated business rejection can remove the optimistic move. Explain the reason beside the affected task and retain information the user can correct. If the operation included a comment, do not discard the text just because the move failed. Recovery should restore a valid product state while preserving the user's effort.
Use the current confirmed base when removing the failed intent. Suppose another task has already moved successfully since the first request started. Restoring the entire old board would undo that unrelated success visually. A mutation-specific rollback changes only the effect owned by the rejected operation.
Conflicts require more context than a generic error toast. If another user changed the task revision, fetch the current version and explain what changed. The product may allow the user to reapply the move, or it may require reconsidering a workflow rule. Automatically overwriting the new revision defeats the reason for detecting the conflict.
Represent uncertainty without inventing success
A timeout can occur before or after commit. Show a bounded pending or confirmation-needed state and query the operation status if the API supports it. If the API uses idempotency, repeat the same intended mutation with the original identity according to its contract. Creating a new identity transforms recovery into another business action.
Define how long the interface keeps trying automatically and what the user can do afterward. A page reload should not necessarily erase an important unresolved operation. For high-value changes, persist a small recovery record or expose server-side operation status so another session can discover the outcome. Avoid storing sensitive request bodies unnecessarily in browser storage.
Do not imply that the optimistic state is saved while it remains uncertain. Use text and accessible status announcements, not color alone. A label such as “Confirming move” tells the user why a dependent action may be unavailable. Keep any blocking local to the affected entity where possible; one uncertain task should not freeze the entire board.
Make late responses harmless
Now let the same user move the task to Active and immediately to Review. The first response arrives after the second. Without operation identities or revisions, that older response can overwrite the newer screen state. Choose a policy: serialize writes to the same entity, coalesce compatible intent, or reconcile responses using explicit revisions and operation ordering.
Serialization is often the easiest policy to explain for consequential changes. The second intent remains visible locally but is submitted only after the first resolves. Coalescing can work for replaceable preferences, such as a final selected label, but is inappropriate when every intermediate action has a business effect. A workflow transition may send a notification or create an audit event.
Test a response lost after commit, a confirmed rejection, two reordered responses, a server-side concurrent edit, and a page reload while confirmation is pending. Assert both displayed state and persisted business state. A test that only checks that a card moved quickly misses the recovery contract.
The tenant-aware idempotency guide develops the API side of mutation identity. The Next.js API boundary guide explains where that contract belongs. Product implementation connects these server guarantees to an interface that remains useful when the network is unreliable.