What you'll learn: By the end of this lesson you will be able to decide when an optimistic update is a sound bet, describe three ways to build one (render from the mutation, snapshot and restore the cache, keep a pending list), explain why rollback should be a deletion rather than an undo, handle responses that arrive out of order, use React 19's
useOptimisticwith its Action rules, and design the failure experience so a rejected change is never silent.
You are booking an appointment by phone and, while the receptionist checks the system, you write it in your diary in pencil. If the clinic confirms, you go over it in ink. If the clinic declines, you rub it out. Now suppose you pencilled in two appointments, the clinic declines the first and confirms the second. A careless diary-keeper who "restores the page as it was before the first booking" also rubs out the second. And if the clinic's two confirmation letters arrive in the wrong order, you must not let the older one overwrite the newer.
An optimistic update is that pencil entry. The page shows the result of an action immediately, before the server has answered, and reconciles when the answer comes. The reason is latency: on a slow network a round trip is long enough to make a click feel broken, and most writes succeed. The price is that you have made a bet, and a bet needs a plan for losing it.
The running example is a listing editor in a seller dashboard. The seller renames a product listing (a title field) and presses "Like" on a customer review (a counter). Both should change on screen at once. All numbers are illustrative.
The core idea
Three statements carry the lesson.
- An optimistic update is a prediction, not a fact. The screen shows what the server is expected to say. The server stays the authority, and the page must be ready for "yes", "no" and "yes, but with a different value".
- Keep what the server confirmed apart from what the user hoped for. Hold a
confirmedcopy and a list ofpendingchanges, and render the confirmed data with the pending changes replayed on top. Then "roll back" does not mean computing an inverse; it means removing the failed change from the list and rendering again. - Answers are events with an order you do not control. Two requests in flight can be answered in either order, one can fail while the other succeeds, and a read that started earlier can return old data after the write. A correct design says what each of these does to the screen.
This lesson builds on Server State: Caching and Revalidation: the confirmed data is usually a query-cache entry, and "settle by refetching" is invalidation. The doc pages named here are those of TanStack Query, SWR and React as read for this lesson, and the lab models the ideas in plain TypeScript instead of using a library.
When an optimistic update is a good bet
Not every write should be optimistic. Ask three questions.
- How likely is success? A like or a rename rarely fails. A payment often does, for reasons the page cannot see.
- Is it reversible, and what does a wrong display cost? Showing a title for a second that is then reverted is cheap. Showing "Order placed" before the order exists is not.
- Can the UI recover clearly? If a failure can be shown at the place the user is looking, an optimistic update is safe. If the user may already have left the page, it needs a notification path.
| Good candidates | Poor candidates |
|---|---|
| Likes, bookmarks, toggles | Payments, bookings, anything that spends money or stock |
| Renaming, reordering, editing text | Actions whose result the server computes (a total, a price) |
| Adding a comment to a list | Actions that need server validation the client cannot predict |
| Deleting a row the user can undo | Irreversible deletion without an undo path |
A middle path exists for the poor candidates: show a pending state ("Saving...") rather than the final value. The user gets instant feedback without a claim that the change has happened.
The anatomy of one optimistic write
Figure 1. One write, two endings
remember it as pending S->>API: PUT title "Final" alt server accepts API-->>S: 200 (maybe a normalised value) Note over S: confirm: update confirmed data,
drop the pending entry else server rejects or request fails API-->>S: 403 or network error Note over S: fail: drop the pending entry,
show the old title and an error end
How to read this: the screen changes before the request returns, and the two possible endings are symmetrical. In both, the pending entry is removed. The only difference is whether the confirmed data changed.
Every optimistic design needs these four steps in some form: apply (show it now), send, confirm (the server accepted, possibly with a different value) and fail (the server rejected or the request did not complete). The designs below differ in where the pending change lives.
Three ways to build it
Way 1: render from the mutation
The simplest approach never touches the cache. TanStack Query's optimistic updates guide describes it as the "via the UI" approach: read the mutation's variables and isPending and render a temporary item (for example with reduced opacity) while the mutation is pending. When the mutation settles, the temporary item disappears and the refetched data shows the real item. The guide notes that variables are not cleared when the mutation errors, so you can keep showing the failed item and offer a retry. There is no rollback code, because nothing was changed. The cost is that only the component that owns the mutation shows the change; other components that display the same list will not.
Way 2: snapshot, patch the cache, restore on error
When several components must show the change, the guide's second approach patches the cache directly. Its steps, in order, are the documented recipe:
- In
onMutate(which runs before the request), cancel in-flight refetches withcancelQueries, so a request that started earlier cannot overwrite the optimistic value. - Snapshot the current cached value with
getQueryData. - Apply the optimistic value with
setQueryData. - Return the snapshot as a context object, which TanStack passes to later handlers.
- In
onError, restore the snapshot. - In
onSettled, runinvalidateQueriesso the cache refetches and matches the server ("always refetch after error or success", in the guide's words).
Each step answers a failure mode, and the lesson on server state is the prerequisite for reading them. Cancelling matters because, by default, a query that becomes unused before it resolves is not cancelled (TanStack's cancellation guide), and an in-flight read of the old value can land after your patch. Refetching at the end matters because your prediction may differ from the server's result.
Way 2 has a flaw that shows up with concurrent writes. A snapshot is "the value before this change". Suppose a seller renames a listing twice in quick succession. The second change snapshots a value that already contains the first, optimistic, title. If the first request then fails, restoring its snapshot erases the second change as well. If the second fails after the first has already failed and been rolled back, restoring the second's snapshot brings back the first title, which the server rejected. A restore is only right when it is the only write in flight.
Way 3: keep confirmed data and a pending list
The lab's design removes the problem by never storing a snapshot. State holds two things:
confirmed: what the server has said is true.pending: changes the user made that the server has not answered, oldest first.
What the screen shows is view(state): the confirmed data with each pending change replayed on top, in order. Rolling back a failed change is deleting it from pending; the view is recomputed, and any other pending change still applies. Nothing needs to remember an old value.
Figure 2. Confirmed data plus pending changes gives the view
How to read this: the user adds to the pending list, the view is always computed from the two stores, and a server answer either moves a change into confirmed data (confirm) or removes it from pending (fail).
In the lab, a change is set or delete on a key, the reducer handles three actions, and a small store wraps it with getState, dispatch and subscribe (the shape React's useSyncExternalStore expects):
- apply gives the change a request id and an increasing sequence number and appends it to
pending. A duplicate dispatch of the same id is ignored. - confirm removes the change from
pendingand, if its sequence number is newer than the last confirmation for that key, writes its value (the server's value, if the server normalised it) intoconfirmed. - fail removes the change from
pendingand records a failure so the UI can say what did not save.
Illustration 1: a minimal example. One title, one change, one answer. The "happy path" and "rollback" scenarios in the captured output below show it: apply title="Final" and the screen changes while the server-confirmed data still says Draft; confirm, and both say Final; or fail with a 403, and the screen says Draft again with failures=1. The "normalises the value" scenario adds the third ending: the user typed " Final ", the server says "Final", and the screen replaces the guess with the server's value.
Out-of-order answers
Two writes in flight is where designs diverge. Suppose the seller saves "Final" (r1), then "Final v2" (r2), and the server holds "Final v2" at the end. The answers can still arrive in either order.
Illustration 2: a realistic example, two saves. The simplest design shows whatever the latest reply says ("last answer wins"). If the answer to r1 arrives after the answer to r2, that design sets the screen back to "Final" while the server holds "Final v2". The seller sees a title that is wrong, and nothing has failed.
Figure 3. Answers that swap places
(last-answer-wins would show "Final")
How to read this: the order of arrival is not the order of the writes. The sequence number records the order of the writes, and the client uses it to decide which answer still matters.
The lab's rules are two:
- A confirmation updates
confirmed[key]only if its sequence number is newer than the last confirmation for that key. An older answer is dropped. - A pending change older than a confirmed change to the same key is superseded.
viewskips it, so the screen does not flicker back to the old value while that older response is still in flight, and a later failure of the superseded change is not reported as an error.
These rules rest on a stated assumption: the server applies one client's changes to a key in the order they were sent. If it cannot promise that, sequence numbers on the client are not enough and you need server-side versions that the server compares, so a stale write is rejected as a conflict. That is a server contract, and the other-side section below points to where such guarantees are taught.
Illustration 3: a failure case, fail after a confirm and fail before one. Two more schedules from the output. If r1 fails while r2 is pending, the screen keeps "Final v2" because r2 is still on top, and the failure of r1 is reported. If r1 is confirmed and then r2 fails, the screen falls back to "Final", the last confirmed value, which is the server's real state. The naive design in the second demo shows "Draft" in that situation, a value from before both writes. The captured output at the end of the lesson shows both.
Figure 4. What happens when an answer arrives
pending?"} B -->|"no (duplicate or unknown)"| X["Ignore"] B -->|"yes"| C{"Confirm or fail?"} C -->|"confirm"| D{"seq newer than last
confirmation for the key?"} D -->|"yes"| E["Remove from pending,
write value to confirmed"] D -->|"no (older answer late)"| F["Remove from pending only"] C -->|"fail"| G{"Superseded by a newer
confirmed change?"} G -->|"yes"| H["Remove from pending,
no error shown"] G -->|"no"| I["Remove from pending,
record a failure to show"]
How to read this: every branch removes the request from the pending list, so a duplicate response is harmless. The branches differ only in whether confirmed data changes and whether the user is told something failed.
React 19: useOptimistic
React 19 has a hook for the most common case. useOptimistic(value, reducer) returns an optimistic state that equals value unless an Action is pending, in which case it equals what reducer(currentState, action) returns. React's documentation says:
- The setter must be called inside an Action (a function passed to
startTransition, which may beasync); outside one, the optimistic state shows briefly and reverts. - The optimistic state renders only while the Action is in progress. When it finishes,
valueis rendered, and the optimistic and real state converge in the same render; there is no extra render to clear it. - If the Action throws, the Transition still ends and React renders with whatever
valuecurrently is. Because the parent usually updatesvalueonly on success, a failed Action leaves the UI showing what it showed before. You can catch the error to show a message. - The reducer must be pure, and if
valuechanges while the Action is pending, React re-runs the reducer with the new value, so optimistic additions stay on top of the latest data.
Two caveats from startTransition's page matter here. State updates after an await inside the Action must be wrapped in another startTransition, and when several Transitions are ongoing, React currently batches them together. The lab's like button follows the first rule when it sets the real count after the reply.
useOptimistic gives you the apply and the automatic revert. It does not give you the other half: it does not order answers, does not tell you which of two overlapping Actions failed, and does not hold a failure for the user. In the lab, two clicks in flight stack both +1 on the shown count, and when answers are swapped without a guard, the older reply moves the real count backwards. A guard that ignores a reply older than one already applied fixes it, and that guard is the sequence number from the previous section.
SWR offers the same bet at the cache level: its mutation docs describe an optimisticData option to update local data while the remote mutation finishes, and a rollbackOnError option to control when data is rolled back. Neither library's docs, as read, say how they resolve the swapped-answers case, so treat that as something to test in the library you adopt.
After it settles: reconcile
An optimistic value is a guess; the settled state should be the server's. Three practices:
- Use the server's value when it differs. If the server trims or normalises, replace the guess (the "normalises" scenario).
- Refetch after the write. TanStack's recipe ends with
invalidateQuerieson both success and error, because the cache may have drifted. Patching the cache from the mutation's response (TanStack's "updates from mutation responses") saves a request, but only when the response is the whole new value. - Do not retry blindly. TanStack does not retry a mutation on error by default. A retry is safe only if the operation is idempotent: MDN defines an HTTP method as idempotent if several identical requests have the same intended effect as one, lists
PUTandDELETEamong them, and saysPOSTandPATCHare not guaranteed to be. A retriedPOSTcan create the item twice unless the server accepts an idempotency key.
Designing the failure
A rejected optimistic change is a bug the user will see, so it needs a designed experience.
- Say what did not save, where the user is looking. In the lab, each failure renders an alert with the rejected value and the reason, and a "Saving..." status shows while a change is pending.
- Do not drop the user's input. Keep the rejected value available for a retry; TanStack's guide keeps
variablesafter an error for this reason. - Mark the pending state honestly. A subtle "saving" cue tells users the value is not final.
- Think about leaving the page. A pending change that fails after the user has navigated away needs a place to report it, or a rule that blocks navigation while saves are pending.
Figure 5. Choosing an approach
the change?"} -->|"only the component
that wrote"| A["Render from the mutation
(variables, isPending)"] Q1 -->|"several components"| Q2{"Can writes overlap
or answers reorder?"} Q2 -->|"no, one at a time"| B["Patch the cache,
snapshot and restore"] Q2 -->|"yes"| C["Pending list:
request ids and sequence numbers"] A --> Q3{"One value inside a
React Action?"} Q3 -->|"yes"| D["useOptimistic
(plus a stale-reply guard)"]
How to read this: start from who has to show the change, then from whether answers can overlap. The more concurrency, the more bookkeeping the design needs.
The other side of this topic
On the back end, an optimistic client meets the server's consistency rules: whether the write is visible to the next read, whether replicas lag, and whether a retry is safe. The course's back-end lessons on consistency models and on idempotent and commutative operations cover the guarantees a client can rely on. The client's pending list is a local version of the same idea: acknowledged, not yet acknowledged, and rejected.
Trade-offs
| Decision | Leans towards | Cost |
|---|---|---|
| Optimistic update | Instant feel, hides latency | A visible reversal when it fails; more state to keep correct |
| Show "Saving..." instead | Honest, simple | The user waits for the final value |
| Render from the mutation | No rollback logic | Only the owning component shows the change |
| Snapshot and restore | Several components show it, little code | Wrong under overlapping writes |
| Pending list with ids | Correct under overlap and reordering | More code and tests; relies on the server applying writes in order, or on versions |
useOptimistic |
Built in, automatic revert | No ordering, no failure list |
| Refetch after settle | Matches the server | An extra read per write |
Build it: confirm, roll back and survive reordering
Goal. Watch the pending-list design handle success, rejection, a normalised value, swapped answers and a failure of the older or the newer of two writes, and compare it with a "last answer wins" design on three schedules.
Setup. Two labs in the course's example workspace: optimistic-update (the reducer, store and mutator, no React) and optimistic-react (React 19 with Testing Library in jsdom, plus a no-React demo that compares the two strategies). Both need Node.js (the traces were captured on Node 26.12.1) and pnpm.
cd examples/frontend
pnpm install
pnpm --filter ./labs/optimistic-update test # 20 tests: reducer cases, every order of three confirmations, the store
pnpm --filter ./labs/optimistic-react test # 12 tests: useOptimistic like button (6), the store in React (6)
cd labs/optimistic-update && node src/demo.ts # seven scenarios
cd ../optimistic-react && node src/demo.ts # three schedules, two strategies
Steps.
- Run the first demo. In each scenario read the
screen=,server-confirmed=andpending=columns. In "happy path", the screen changes at theapplyline andserver-confirmedcatches up at theconfirmsline. - In "rollback", find the line where the screen returns to
Draftandfailures=1. Note that nothing computed an inverse: the pending entry was removed. - In "out-of-order responses", the answer to
r1arrives last. Compare the screen before and after that line. - In the last two failure scenarios, compare which title remains and whether
failuresis 1. - Run the second demo. For each schedule, compare "last answer wins" with "request ids". In schedule B the first design ends on the wrong title while the server holds "Final v2". In schedule C the first design ends on "Draft" instead of "Final".
Expected output, captured from a real run (first demo, Node 26.12.1, 2026-11-07):
=== happy path: the screen changes first, the server catches up
start screen={"title":"Draft"} server-confirmed={"title":"Draft"} pending=[] failures=0
apply r1 set title="Final" screen={"title":"Final"} server-confirmed={"title":"Draft"} pending=[r1:set title=Final] failures=0
server confirms r1 screen={"title":"Final"} server-confirmed={"title":"Final"} pending=[] failures=0
=== rollback: the server rejects the change
start screen={"title":"Draft"} server-confirmed={"title":"Draft"} pending=[] failures=0
apply r1 set title="Final" screen={"title":"Final"} server-confirmed={"title":"Draft"} pending=[r1:set title=Final] failures=0
server fails r1 (403 forbidden) screen={"title":"Draft"} server-confirmed={"title":"Draft"} pending=[] failures=1
=== server normalises the value
start screen={"title":"Draft"} server-confirmed={"title":"Draft"} pending=[] failures=0
apply r1 set title=" Final " screen={"title":" Final "} server-confirmed={"title":"Draft"} pending=[r1:set title= Final ] failures=0
server confirms r1 (as "Final") screen={"title":"Final"} server-confirmed={"title":"Final"} pending=[] failures=0
=== out-of-order responses: the older answer arrives last and is ignored
start screen={"title":"Draft"} server-confirmed={"title":"Draft"} pending=[] failures=0
apply r1 set title="Final" screen={"title":"Final"} server-confirmed={"title":"Draft"} pending=[r1:set title=Final] failures=0
apply r2 set title="Final v2" screen={"title":"Final v2"} server-confirmed={"title":"Draft"} pending=[r1:set title=Final, r2:set title=Final v2] failures=0
server confirms r2 screen={"title":"Final v2"} server-confirmed={"title":"Final v2"} pending=[r1:set title=Final] failures=0
server confirms r1 screen={"title":"Final v2"} server-confirmed={"title":"Final v2"} pending=[] failures=0
=== the older change fails while a newer one is still pending: the newer one stays on screen
start screen={"title":"Draft"} server-confirmed={"title":"Draft"} pending=[] failures=0
apply r1 set title="Final" screen={"title":"Final"} server-confirmed={"title":"Draft"} pending=[r1:set title=Final] failures=0
apply r2 set title="Final v2" screen={"title":"Final v2"} server-confirmed={"title":"Draft"} pending=[r1:set title=Final, r2:set title=Final v2] failures=0
server fails r1 (network error) screen={"title":"Final v2"} server-confirmed={"title":"Draft"} pending=[r2:set title=Final v2] failures=1
server confirms r2 screen={"title":"Final v2"} server-confirmed={"title":"Final v2"} pending=[] failures=1
=== the newer change fails after the older one was confirmed: back to the last confirmed value
start screen={"title":"Draft"} server-confirmed={"title":"Draft"} pending=[] failures=0
apply r1 set title="Final" screen={"title":"Final"} server-confirmed={"title":"Draft"} pending=[r1:set title=Final] failures=0
apply r2 set title="Final v2" screen={"title":"Final v2"} server-confirmed={"title":"Draft"} pending=[r1:set title=Final, r2:set title=Final v2] failures=0
server confirms r1 screen={"title":"Final v2"} server-confirmed={"title":"Final"} pending=[r2:set title=Final v2] failures=0
server fails r2 (500) screen={"title":"Final"} server-confirmed={"title":"Final"} pending=[] failures=1
=== delete, then a duplicate response is harmless
start screen={"title":"Draft"} server-confirmed={"title":"Draft"} pending=[] failures=0
apply r1 delete title screen={} server-confirmed={"title":"Draft"} pending=[r1:delete title] failures=0
server confirms r1 screen={} server-confirmed={} pending=[] failures=0
server confirms r1 screen={} server-confirmed={} pending=[] failures=0
Expected output, captured from a real run (second demo, Node 26.12.1, 2026-11-08):
=== A. two saves, answers in the order sent
The server saved "Final" and then "Final v2". Both strategies end on "Final v2".
last answer wins:
start screen="Draft"
send r1 "Final" screen="Final"
send r2 "Final v2" screen="Final v2"
server answers r1: ok screen="Final"
server answers r2: ok screen="Final v2"
request ids:
start screen="Draft" confirmed="Draft" pending=[] failures=0
send r1 "Final" screen="Final" confirmed="Draft" pending=[r1] failures=0
send r2 "Final v2" screen="Final v2" confirmed="Draft" pending=[r1,r2] failures=0
server answers r1: ok screen="Final v2" confirmed="Final" pending=[r2] failures=0
server answers r2: ok screen="Final v2" confirmed="Final v2" pending=[] failures=0
=== B. two saves, the answers swap places
The server saved "Final" and then "Final v2", but the answer to r1 arrives last. The server's truth is "Final v2".
last answer wins:
start screen="Draft"
send r1 "Final" screen="Final"
send r2 "Final v2" screen="Final v2"
server answers r2: ok screen="Final v2"
server answers r1: ok screen="Final"
request ids:
start screen="Draft" confirmed="Draft" pending=[] failures=0
send r1 "Final" screen="Final" confirmed="Draft" pending=[r1] failures=0
send r2 "Final v2" screen="Final v2" confirmed="Draft" pending=[r1,r2] failures=0
server answers r2: ok screen="Final v2" confirmed="Final v2" pending=[r1] failures=0
server answers r1: ok screen="Final v2" confirmed="Final v2" pending=[] failures=0
=== C. the second save fails after the first was confirmed
The server really holds "Final". The screen should say so.
last answer wins:
start screen="Draft"
send r1 "Final" screen="Final"
send r2 "Final v2" screen="Final v2"
server answers r1: ok screen="Final"
server answers r2: 500 screen="Draft"
request ids:
start screen="Draft" confirmed="Draft" pending=[] failures=0
send r1 "Final" screen="Final" confirmed="Draft" pending=[r1] failures=0
send r2 "Final v2" screen="Final v2" confirmed="Draft" pending=[r1,r2] failures=0
server answers r1: ok screen="Final v2" confirmed="Final" pending=[r2] failures=0
server answers r2: 500 screen="Final" confirmed="Final" pending=[] failures=1
What the labs do not show. Everything here is a model. The state machine is plain TypeScript with fake server answers that the script decides, and the React tests run in jsdom, a JavaScript model of the DOM: there is no network, no real timing and no screen, so nothing about layout, focus or how a change looks was seen. The labs use the store of the first lab and React's useOptimistic directly; they do not run TanStack Query or SWR, and do not show how those libraries order swapped answers. The server is assumed to apply one client's writes to a key in the order they were sent. The "last answer wins" strategy in the second demo is a deliberately naive baseline written for the lab, not a model of any library.
Break it. In optimistic-update/src/reducer.ts, in the confirm case, delete the line that returns early when found.seq <= lastSeq ("an older answer arriving late"). Run the tests of that lab: four fail, including the property test over every order of three confirmations, because a late, older confirmation now overwrites the newer value. Restore the line and run the tests again.
Stretch. Pick one:
- Replace the client sequence number with a server-assigned version and reject a confirmation that does not match the expected one, surfacing it as a conflict in
failures. - Add a
retryfor a failed change that keeps its place inpendinginstead of rolling back. - Add the snapshot-and-restore approach beside the store and write the test that fails when two writes overlap.
In practice: renaming listings in a seller dashboard
This is a realistic scenario, not a case history. It is a composite built from common production patterns. It describes no specific company or product, and every number in it is an illustrative assumption.
The situation
A marketplace's seller dashboard lets sellers rename product listings inline. The title input saves on blur, and the list shows the new title as soon as the request is sent. Most sellers are on laptops, but a growing share edit on phones with unreliable connections. Support tickets say "my title keeps changing back" and "it said saved but the old name is on the site". Telemetry shows the save endpoint answers in under a second for most requests, with a long tail on mobile networks (illustrative: a few seconds). Three engineers own the editor.
Starting architecture
The dashboard keeps the list in a query cache. The save handler snapshots the list in onMutate, patches the title, restores the snapshot in onError and invalidates on settle.
Figure 6. Snapshot and restore on every save
How to read this: the warning box holds the only copy of "what it was before". With two saves in flight it holds a snapshot that already contains the first save.
Options considered
| Option | What it fixes | What it costs | Risk |
|---|---|---|---|
| Keep snapshot and restore, disable the input while saving | No overlapping writes | Sellers cannot keep typing; slow on bad networks | Blocks the user on exactly the slow connections |
| Pending list with request ids and sequence numbers | Overlap, reordering and partial failure are handled | A small state module and tests; stays correct only if the server applies writes in order | The server contract must hold |
| Server versions with conflict responses | Correct even if the server reorders | An API change and a conflict UI | Needs the server team |
| Pessimistic: wait for the answer | No wrong display | Slow feel | Users abandon edits on mobile |
The decision
| Field | Decision record |
|---|---|
| Context | Overlapping saves on slow connections produce reverted titles and silent failures, caused by shared snapshots and "last answer wins". |
| Decision | Replace snapshot and restore for title edits with a pending list: request ids, sequence numbers, view replay. Show a "Saving..." status while pending and an alert naming the rejected value. Refetch after the list settles. Ask the server team for versions as a follow-up. |
| Consequences, good | A failed or late save cannot erase a newer one; failures are visible. |
| Consequences, bad | More client code to maintain; relies on in-order server writes until versions ship. |
| Revisit when | The server provides version numbers, or edits are made from several devices at once, where the client cannot know the order. |
Rollout and verification
- Reproduce first. Use the network panel's throttling to delay the first request and answer the second one earlier, then confirm the title reverts.
- Port the reducer tests from the lab: every order of three confirmations, a fail while another change is pending, and a duplicate response.
- Ship behind a flag to a small share of sellers and compare support tickets and the rate of "could not save" alerts.
- Test the failure UI with the keyboard and a screen reader: the alert must be announced and the rejected value must be recoverable.
The 2 a.m. failure
A seller on a train sends two renames; the first request hangs, the second succeeds. Eventually the first request's connection recovers and the server applies it, after the second: the server now holds the older title. The client's sequence numbers cannot know that: both answers were "ok", in order r2, r1, and the client shows the newer title. A refresh shows the old one.
The cause is the stated assumption. The client orders answers, but the server did not apply the writes in the order they were sent. First three checks: (1) compare server write timestamps for the two requests; (2) look at what the save endpoint does with a write that arrives late; (3) check whether the client can send a second save for the same listing before the first has settled. Mitigation: serialise saves per listing on the client (send the next only after the previous settles) as a stop-gap. Follow-up: add a version to the listing and reject writes that do not match, so the client gets a conflict instead of silent loss.
Architect's notes
- Decide the bet per action. Write down which actions are optimistic, which show "pending", and which wait. Payments and stock are the usual "wait".
- Keep confirmed and pending apart. A pending list makes rollback a deletion and makes concurrent writes safe by construction.
- Name the server contract. "Writes to one key apply in the order sent" is an assumption. If it is not true, you need versions, and that is an API conversation, not a client trick.
- Make failure a first-class state. Design the alert, the retry and the accessibility before the happy path ships.
- Test the schedules, not only the outcomes. Deliver answers in every order and look at the screen between answers, because a flicker is a bug that final-state assertions miss.
Common mistakes
- Restoring a snapshot when writes can overlap. The snapshot already contains other optimistic changes.
- Letting the last answer win. It reverts the screen to an older value when answers reorder.
- Optimism without a failure path. The change is silently reverted and the user has no idea why.
- Forgetting to cancel in-flight reads. A read that started before the write can land afterwards and replace the optimistic value.
- Retrying a non-idempotent request. A
POSTretried after a timeout can create two items. - Calling the
useOptimisticsetter outside an Action. The optimistic state flashes and reverts. - Skipping the refetch. The prediction and the server's result can differ in ways only the server knows.
Key takeaways
- An optimistic update shows the expected result before the server answers; it is a bet on success and needs a plan for failure.
- Keep confirmed data and a pending list apart; the screen is the confirmed data with pending changes replayed on top, and rollback is removing a pending change, not computing an undo.
- Snapshot and restore is correct only when writes do not overlap; with overlap it erases or resurrects the wrong values.
- Give each change a request id and sequence number, and ignore a confirmation older than one already applied; a failed change that was superseded is not an error.
useOptimisticshows the optimistic value while an Action is pending and reverts when it ends or throws; it does not order answers or keep a failure list.- Reconcile after the write: take the server's value, refetch, and retry only idempotent requests.
- Design the failure experience: say what did not save, keep the input, and make it accessible.
Practice exercises
Exercise 1 — Starter (30 min): For a social feed, classify five actions (like, comment, delete post, send payment, change username) as optimistic, "show pending", or wait. Give one sentence of reasoning for each.
Exercise 2 — Intermediate (2 hours): Run the optimistic-update tests. Then write down, by hand, the screen after each step of the schedule "r1 apply, r2 apply, r2 confirm, r1 fail" before you run the demo scenario that shows it, and note where your prediction differed.
Exercise 3 — Advanced (half day): Implement the snapshot-and-restore approach beside the pending-list store, write a test with two overlapping saves where the first fails, and record which tests fail. Then add server-assigned versions to the pending-list store and handle a rejected stale write as a conflict.
Related reading
In this course:
- Server State: Caching and Revalidation — the cache whose entries these updates patch and then refetch.
- React Hooks Internals — how hooks such as
useOptimisticanduseSyncExternalStoreare stored and re-run. - Server Actions and Server-Driven Mutations — mutations that start on the server side of a React app.
- React Effects and Synchronization — when to synchronise state with an external system.
The other side of the topic:
- Backend: Consistency Models — what a client may assume about a write that has been acknowledged.
- Backend: Idempotent and Commutative Operations — making a retry safe on the server.
Official documentation
- TanStack Query: Optimistic Updates — the UI approach and the cache approach.
- TanStack Query: Mutations — lifecycle callbacks and retry behaviour.
- React: useOptimistic and startTransition.
- SWR: Mutation —
optimisticDataandrollbackOnError. - MDN: Idempotent — which HTTP methods are safe to repeat.