Frontend Component and State Architecture Questions
Structuring client applications for maintainability: component architecture and code organization (composition and compound components, container/presentational split, controlled vs uncontrolled components, prop drilling and context, refs and imperative handles, folder and module boundaries as a codebase grows), state management and data flow (local vs global state, state colocation and lifting, reducers and stores, selectors and derived state, normalization, immutability, one-way flow, migrating a legacy global store incrementally), how the UI framework turns state into screen updates (hooks and effect dependencies, re-render behaviour, memoization trade-offs, keys, update batching, concurrent rendering and transitions, plus the same ideas in Angular services and change detection), data-fetching patterns (server-state caching, stale-while-revalidate, optimistic updates and rollback, request deduplication, cursor pagination, normalized GraphQL caches, merging live socket events and partial failures into local state, undo and redo history), URL state and route-scoped data, micro-frontends and cross-team state ownership and isolation, framework-agnostic web components, event-bus communication between distant widgets, and rendering strategy trade-offs (CSR, SSR, hydration and mismatches, progressive enhancement). Covers designing a frontend that scales in complexity without becoming brittle. Reusable component libraries as design systems, form and dialog implementation, accessibility practice, render-speed tuning, language typing mechanics, browser storage APIs and offline persistence, conflict-resolution protocols for collaborative editing, and testing strategy are covered elsewhere.
Define optimistic versus pessimistic updates. Give two cases where each is the better choice, and say what the user should see when an optimistic update fails.
Sample Answer
Direct answer
An optimistic update changes the screen immediately, as if the server had already accepted the action, then sends the request and corrects the screen if it fails. A pessimistic update waits for the server's answer before changing the screen, usually showing a pending state meanwhile. Choose optimistic when the action almost always succeeds, is cheap to undo, and the server adds nothing the user needs to see; choose pessimistic when failure is plausible, the effect is costly or irreversible, or the result depends on something only the server knows. When an optimistic update fails, the user should see their change reverted, a short message next to where they acted saying what did not save, and a way to retry without retyping.
Two cases where each is better
| Update style | Case | Why it fits |
|---|---|---|
| Optimistic | Liking, bookmarking or ticking a checkbox | Succeeds almost always, one tap undoes it, a wrong count for a second harms nobody |
| Optimistic | Dragging a card to a new column on a board | The result is visible only after the move, and waiting would make the drag feel broken. The server's rejection is rare and the card can slide back |
| Pessimistic | Paying for an order or transferring money | Failure is plausible (declined card), the effect is costly, and showing "Paid" and then taking it back damages trust |
| Pessimistic | Booking the last seat or claiming a unique username | Only the server knows whether it is still free, so any optimistic answer is a guess that will often be wrong, and the server may also assign the id, price or confirmation number |
Other signals: an action that triggers side effects outside the browser (an email is sent, a permission is granted) is pessimistic even if it usually works. An action that fails often because of validation should be validated on the client first and then treated as optimistic or pessimistic by its remaining failure rate.
Worked example: the like button
The server holds liked = false, count = 41.
- The user taps. The UI shows
liked = true,count = 42at once and remembers what it replaced (false,41). - The request returns 500. The UI restores
false,41, shows "Couldn't save your like. Try again" beside the button, and keeps the button usable. - Whether it succeeds or fails, the reliable last step is to refetch the real value, so the screen ends up matching the server rather than matching the client's guess.
The TanStack Query documentation describes this: when you update optimistically "there is a chance that the mutation will fail", in which case "you can instead choose to roll back your update", and for many failures "you can just trigger a refetch for your optimistic queries to revert them to their true server state" (TanStack Query v5, Optimistic Updates).
What breaks rollback: overlapping updates
Restoring "the previous value" is wrong when two requests for the same item are in flight. Trace it with the like button, starting at liked = false, count = 41:
| Step | Screen | Snapshot saved for rollback |
|---|---|---|
| Tap 1 (like) | liked, 42 | A = (not liked, 41) |
| Tap 2 (unlike) before tap 1 returns | not liked, 41 | B = (liked, 42) |
| Request 1 fails | restore A: not liked, 41 | |
| Request 2 fails | restore B: liked, 42 |
The server never accepted either request, so the true state is not liked, 41, but restoring snapshots left the screen on liked, 42. Two safer designs: refetch when the last in-flight request settles and show the server value, or compute the screen as "server value plus the edits still in flight" and drop only the failed edit. Either way the rollback must be tied to the specific change that failed.
What the user should see on failure, in order
- The value goes back, so the screen never keeps showing something the server does not have.
- A message at the place of the action that names the action ("Couldn't save your like"), not a generic "Error". If the user has already moved to another screen, use a toast (a small message that appears over the screen for a few seconds without blocking it) that identifies the item. On a phone, where the list the user acted on may no longer be visible, the toast carries the whole message: for example "Couldn't save your like on 'Trip to Lisbon'. Tap to retry", with the item's name and a retry action in the same message.
- Their work is not lost. For a typed comment, keep the text in the field and offer Retry; reverting the field to empty would turn a network blip into data loss.
- A way forward: Retry for transient failures (timeouts, and 5xx responses: HTTP status codes from 500 to 599, meaning the server failed rather than the request being wrong), and a specific explanation for rejections the user can fix (validation, permission).
- Announce it to assistive technology, for example by putting the message in an element with
role="alert"(an HTML attribute that makes a screen reader, the software that reads the page aloud to blind users, speak the message as soon as it appears) and test it with a screen reader.
Pessimistic done well
Waiting is not the same as freezing: disable the control, show a spinner or "Saving...", prevent double submission (disable after the first click, or send an idempotency key: a unique token the client attaches to the request so that the server, if it receives the same token twice, performs the action once), and change the screen only on success. If latency is the complaint, a middle path is to show the pending item in a "sending" style and mark it confirmed on success, which is optimistic in layout but honest in state.
Pitfalls
- Optimistic code needs a failure path, a rollback that survives overlapping requests, and a refetch; if a feature will not get all three it is cheaper to be pessimistic.
- Do not make an optimistic update look final: no success toast, confirmation email or navigation until the server confirms.
- Test the failure path deliberately (a mocked 500, an offline toggle), because it is the part that rarely runs in development.
Users edit and create items in your client app and expect instant feedback, but the server may reject or modify what they submitted. How do you design optimistic updates for this, including temporary ids for new items, detecting that the server state has changed underneath the user, and rolling back a rejected change?
Sample Answer
Direct answer
Keep two things apart: the data the server has confirmed, and a list of pending operations the user has asked for. The screen shows the confirmed data with the pending operations applied on top. An optimistic update is then "add an operation to the list and send the request". Rolling back is "delete that one operation from the list", which cannot disturb other pending edits. Confirming is "write the server's response into the confirmed data and delete the operation", so whatever the server changed (trimmed text, a new version number) replaces what the user typed.
For the three things the question names:
- Temporary ids. Give each new item a client-generated key that never changes (in the demo's create test it is
tmp-1), use it as the UI row key, and remember the real id separately once the server replies. A row key is the value the UI framework uses to match a list row to its data between renders; if it changes, the row is remounted (destroyed and created again), which loses focus, scroll position and typed text inside it. With a stable key the row is not remounted when the real id arrives, and edits made before the reply are queued behind the create and sent with the real id. - Detecting that the server state changed. Send the version you last saw with each update. HTTP's own form of this is the
If-Matchrequest header (the server applies the change only if the stored version still matches; MDN documents that a failedIf-Matchgets412 Precondition Failed). This API uses aversionnumber and answers409 Conflict(MDN: "a request conflict with the current state of the target resource") with the current item in the body. - Rolling back a rejected change. Remove that operation and report the error. Do not restore a saved copy of the whole list.
What the API must provide
| Need | Server behaviour used here |
|---|---|
| a version to compare | every item carries version; an update sends ifMatch with the version the client last confirmed |
| conflict detection | 409 with the current item in the body, so the client can show the server's version without another request |
| rejection | 422 for invalid input (MDN: the server understood the request but "was unable to process the contained instructions", and repeating it unchanged will fail again); the client rolls the operation back and shows the message |
| normalised data | the success response returns the stored item as the server saved it (here: whitespace collapsed in the title, version increased), so the client can replace what the user typed |
| create | returns the new item with its real id |
Recommended for a real API: accept an idempotency key (a unique token the client sends with a create; the server remembers it and returns the first result if the same token arrives again) so that a retry after a timeout cannot create two items. The demo's fake server does not model this.
Why a pending list and not a saved copy
The common shortcut is to save a copy of the list before the change and restore it if the request fails. It breaks as soon as two requests overlap. The last test in the demo shows it: request 1 changes item one and will fail, request 2 changes item two and will succeed. Restoring request 1's copy puts item two back to its old value on screen although the server stored the new one. With a pending list, request 1's failure deletes request 1's operation and nothing else.
Request ordering
Requests for the same item run one at a time. The second update waits for the first, so it can send the version the first one produced, and an update made to an unconfirmed new item waits for the create so that it can use the real id. Requests for different items run independently.
How the demo works
enqueue(key, job)keeps one promise chain per item key. A new job starts only when the previous job for that key has finished (.then(job));next.catch(() => {})stores a version of the chain that cannot reject, as a safety net for a job that throws outside its owntryblock. Every job in this demo handles its own errors, so no test reaches that line (deleting it leaves all seven tests passing); a rejected request does not stop later ones because each job catches its own failure in itstry/catch/finally. Different keys have different chains, which is why unrelated items run independently.view()starts from the confirmed data and applies each pending operation on top, marking those itemspending: true. Nothing is ever restored; the screen is recomputed.- The fake server in the second listing does not answer by itself. Each call to
api.createorapi.updateis recorded insentand parked inwaiting;server.next()answers the oldest parked request (after yielding withsetImmediateso the store has time to send it). That lets a test hold a request in flight, check the screen, then choose when the server replies.
Demo
First file, optimistic_store.mjs:
// Confirmed server data plus a list of pending operations. The screen shows confirmed + pending.
// Rolling back means deleting one pending operation; everything else stays applied.
export function createOptimisticStore(api) {
const confirmed = new Map(); // key -> { key, id, title, version } (key is stable, id may be null)
let order = []; // keys in display order
let pending = []; // [{ opId, type: 'create' | 'update', key, patch }]
const conflicts = []; // [{ key, mine: [patch...], theirs }]
const errors = []; // [{ key, patch, message }]
const queues = new Map(); // key -> promise chain, so one entity's requests run in order
let seq = 0;
const enqueue = (key, job) => {
const next = (queues.get(key) ?? Promise.resolve()).then(job);
queues.set(key, next.catch(() => {}));
return next;
};
const drop = (op) => { pending = pending.filter((p) => p !== op); };
const isLive = (op) => pending.includes(op);
function view() {
const items = new Map([...confirmed].map(([k, v]) => [k, { ...v, pending: false }]));
const keys = [...order];
for (const op of pending) {
if (op.type === 'create') { items.set(op.key, { key: op.key, id: null, version: 0, ...op.patch, pending: true }); keys.push(op.key); }
else if (items.has(op.key)) items.set(op.key, { ...items.get(op.key), ...op.patch, pending: true });
}
return keys.filter((k) => items.has(k)).map((k) => items.get(k));
}
function load(items) {
for (const it of items) { confirmed.set(it.id, { key: it.id, ...it }); order.push(it.id); }
}
function create(fields) {
const op = { opId: ++seq, type: 'create', key: `tmp-${seq}`, patch: fields };
pending.push(op);
enqueue(op.key, async () => {
try {
const saved = await api.create(fields);
confirmed.set(op.key, { key: op.key, ...saved }); order.push(op.key); // the key never changes, so the UI row is not remounted
} catch (e) {
errors.push({ key: op.key, patch: fields, message: e.message });
} finally { drop(op); }
});
return op.key;
}
function update(key, patch) {
const op = { opId: ++seq, type: 'update', key, patch };
pending.push(op);
return enqueue(key, async () => {
if (!isLive(op)) return; // dropped because an earlier request for this item conflicted
const base = confirmed.get(key);
if (!base) { errors.push({ key, patch, message: 'item was never created' }); drop(op); return; }
try {
const saved = await api.update(base.id, patch, base.version); // If-Match style version check
confirmed.set(key, { key, ...saved }); // the server's version wins, including fields it changed
} catch (e) {
if (e.status === 409) {
const later = pending.filter((p) => p.key === key && p.opId >= op.opId && p.type === 'update');
conflicts.push({ key, mine: later.map((p) => p.patch), theirs: e.current });
confirmed.set(key, { key, ...e.current });
later.forEach(drop);
return;
}
errors.push({ key, patch, message: e.message });
} finally { drop(op); }
});
}
return { load, create, update, view, conflicts, errors, pendingCount: () => pending.length, idOf: (key) => confirmed.get(key)?.id ?? null };
}
Second file, optimistic_demo.mjs:
import assert from 'node:assert/strict';
import { createOptimisticStore } from './optimistic_store.mjs';
// A fake server. Requests wait in a queue; the test decides when each one is answered.
function fakeServer() {
const db = new Map(); let nextId = 100; const waiting = []; const sent = [];
const answer = (name, args, run) => new Promise((resolve, reject) => { sent.push({ name, args }); waiting.push(() => { try { resolve(run()); } catch (e) { reject(e); } }); });
const clean = (t) => t.trim().replace(/\s+/g, ' ');
const reject = (status, message, extra) => Object.assign(new Error(message), { status }, extra);
return {
db, sent,
api: {
create: (f) => answer('create', f, () => {
if (!clean(f.title)) throw reject(422, 'title required');
const item = { id: nextId++, title: clean(f.title), version: 1 }; db.set(item.id, item); return { ...item };
}),
update: (id, patch, ifMatch) => answer('update', { id, patch, ifMatch }, () => {
const cur = db.get(id);
if (cur.version !== ifMatch) throw reject(409, 'conflict', { current: { ...cur } });
if (patch.title !== undefined && !clean(patch.title)) throw reject(422, 'title required');
const item = { ...cur, ...patch, version: cur.version + 1 };
if (patch.title !== undefined) item.title = clean(patch.title);
db.set(id, item); return { ...item };
}),
},
async next() { await new Promise((r) => setImmediate(r)); waiting.shift()(); await new Promise((r) => setImmediate(r)); },
};
}
const titles = (s) => s.view().map((i) => i.title);
const results = [];
async function test(name, fn) { try { await fn(); results.push(`ok ${name}`); } catch (e) { results.push(`FAIL ${name}: ${e.message.split('\n')[0]}`); process.exitCode = 1; } }
const tick = () => new Promise((r) => setImmediate(r));
function setup() {
const server = fakeServer(); const store = createOptimisticStore(server.api);
server.db.set(1, { id: 1, title: 'one', version: 1 }); server.db.set(2, { id: 2, title: 'two', version: 1 });
store.load([{ id: 1, title: 'one', version: 1 }, { id: 2, title: 'two', version: 1 }]);
return { server, store };
}
await test('an edit shows at once, then the server-normalised value replaces it', async () => {
const { server, store } = setup();
store.update(1, { title: ' uno edited ' });
assert.equal(store.view()[0].title, ' uno edited ');
assert.equal(store.view()[0].pending, true);
await server.next();
assert.equal(store.view()[0].title, 'uno edited');
assert.equal(store.view()[0].pending, false);
assert.equal(store.view()[0].version, 2);
});
await test('a rejected edit is rolled back without undoing a different pending edit', async () => {
const { server, store } = setup();
store.update(1, { title: ' ' }); // the server will refuse this (422)
store.update(2, { title: 'two (edited)' }); // unrelated, still in flight
assert.deepEqual(titles(store), [' ', 'two (edited)']);
await server.next(); // answers the first request: rejected
assert.deepEqual(titles(store), ['one', 'two (edited)']);
assert.equal(store.errors.length, 1);
await server.next();
assert.deepEqual(titles(store), ['one', 'two (edited)']);
});
await test('two edits to the same item are sent in order, each with the latest version', async () => {
const { server, store } = setup();
store.update(1, { title: 'a' }); store.update(1, { title: 'b' });
await tick(); assert.equal(server.sent.length, 1); // the second waits for the first
await server.next(); await tick();
await server.next();
assert.deepEqual(server.sent.map((s) => s.args.ifMatch), [1, 2]);
assert.equal(store.view()[0].title, 'b');
assert.equal(server.db.get(1).title, 'b');
});
await test('a new item gets a temporary id, an edit made before the reply is sent with the real id', async () => {
const { server, store } = setup();
const key = store.create({ title: 'draft' });
assert.equal(store.view().length, 3);
assert.equal(store.view()[2].id, null);
store.update(key, { title: 'draft 2' }); // edited before the create has been answered
await tick(); assert.equal(server.sent.length, 1); // only the create has been sent
await server.next(); await tick(); // create answered
assert.equal(store.idOf(key), 100);
assert.equal(store.view()[2].key, key); // the key did not change when the real id arrived
assert.equal(server.sent[1].args.id, 100); // the edit used the real id
await server.next();
const v = store.view();
assert.equal(v.length, 3); // no duplicate row
assert.equal(v[2].key, key); // same key, so the row is not remounted
assert.equal(v[2].title, 'draft 2');
assert.equal(server.db.get(100).title, 'draft 2');
});
await test('a rejected create removes the temporary item and reports the queued edit', async () => {
const { server, store } = setup();
const key = store.create({ title: ' ' });
store.update(key, { title: 'x' });
await server.next(); await tick();
assert.equal(store.view().length, 2);
assert.deepEqual(store.errors.map((e) => e.message), ['title required', 'item was never created']);
});
await test('a 409 shows the server version, keeps the user edits aside and drops later queued edits', async () => {
const { server, store } = setup();
server.db.set(1, { id: 1, title: 'changed elsewhere', version: 2 }); // another client edited item 1
store.update(1, { title: 'mine 1' }); store.update(1, { title: 'mine 2' });
await server.next(); await tick();
assert.equal(store.view()[0].title, 'changed elsewhere');
assert.equal(store.view()[0].version, 2);
assert.deepEqual(store.conflicts[0].mine, [{ title: 'mine 1' }, { title: 'mine 2' }]);
assert.equal(server.sent.length, 1); // the second edit was never sent
assert.equal(store.pendingCount(), 0);
assert.equal(server.db.get(1).title, 'changed elsewhere');
});
await test('contrast: restoring a snapshot on failure also erases a different edit that succeeded', async () => {
let ui = ['one', 'two'];
const edit = (i, v) => { const snapshot = [...ui]; ui[i] = v; return () => { ui = snapshot; }; };
const rollbackFirst = edit(0, 'x'); // request 1 will fail
edit(1, 'y'); // request 2 will succeed on the server
rollbackFirst();
assert.deepEqual(ui, ['one', 'two']); // 'y' is gone from the screen although the server stored it
});
console.log(results.join('\n'));
Output:
ok an edit shows at once, then the server-normalised value replaces it
ok a rejected edit is rolled back without undoing a different pending edit
ok two edits to the same item are sent in order, each with the latest version
ok a new item gets a temporary id, an edit made before the reply is sent with the real id
ok a rejected create removes the temporary item and reports the queued edit
ok a 409 shows the server version, keeps the user edits aside and drops later queued edits
ok contrast: restoring a snapshot on failure also erases a different edit that succeeded
The tests cover: a confirmed edit that the server normalised, a rejected edit next to a different pending edit, two edits to one item, a new item edited before its reply, a rejected create with a queued edit, and a 409 with two queued edits. The seventh test is the saved-copy contrast: it replays the shortcut on a plain array and never runs the store, so it illustrates the failure and does not guard the store. The six store tests are the ones that fail when a technique is removed.
What breaks if a technique is removed
Each edit to optimistic_store.mjs was run against the same demo, which exits with a non-zero code when any test fails:
| Edit | Result |
|---|---|
replace the per-item queue with const next = job(); | four tests fail: same-item ordering, create-then-edit, rejected create, and the 409 test |
call api.update(base.id, patch) with no version | four tests fail (the first four): the server sees a missing version and answers 409 for every update |
delete the finally { drop(op); } in update | the first two tests fail: the edit stays pending after the reply and the rejected edit is not rolled back |
in create, store the saved item under the real id instead of op.key ({ ...saved, key: saved.id }) | the create test fails at the assertion made right after the create reply: the row key changed, so the row would be remounted |
The output of the four runs (node:22, Node 22.23.3) is:
== queue removed
ok an edit shows at once, then the server-normalised value replaces it
ok a rejected edit is rolled back without undoing a different pending edit
FAIL two edits to the same item are sent in order, each with the latest version: Expected values to be strictly equal:
FAIL a new item gets a temporary id, an edit made before the reply is sent with the real id: Cannot read properties of undefined (reading 'args')
FAIL a rejected create removes the temporary item and reports the queued edit: Expected values to be strictly deep-equal:
FAIL a 409 shows the server version, keeps the user edits aside and drops later queued edits: Expected values to be strictly equal:
ok contrast: restoring a snapshot on failure also erases a different edit that succeeded
== version not sent
FAIL an edit shows at once, then the server-normalised value replaces it: Expected values to be strictly equal:
FAIL a rejected edit is rolled back without undoing a different pending edit: Expected values to be strictly equal:
FAIL two edits to the same item are sent in order, each with the latest version: waiting.shift(...) is not a function
FAIL a new item gets a temporary id, an edit made before the reply is sent with the real id: Expected values to be strictly equal:
ok a rejected create removes the temporary item and reports the queued edit
ok a 409 shows the server version, keeps the user edits aside and drops later queued edits
ok contrast: restoring a snapshot on failure also erases a different edit that succeeded
== operation never dropped
FAIL an edit shows at once, then the server-normalised value replaces it: Expected values to be strictly equal:
FAIL a rejected edit is rolled back without undoing a different pending edit: Expected values to be strictly deep-equal:
ok two edits to the same item are sent in order, each with the latest version
ok a new item gets a temporary id, an edit made before the reply is sent with the real id
ok a rejected create removes the temporary item and reports the queued edit
ok a 409 shows the server version, keeps the user edits aside and drops later queued edits
ok contrast: restoring a snapshot on failure also erases a different edit that succeeded
== key changed to the real id
ok an edit shows at once, then the server-normalised value replaces it
ok a rejected edit is rolled back without undoing a different pending edit
ok two edits to the same item are sent in order, each with the latest version
FAIL a new item gets a temporary id, an edit made before the reply is sent with the real id: Expected values to be strictly equal:
ok a rejected create removes the temporary item and reports the queued edit
ok a 409 shows the server version, keeps the user edits aside and drops later queued edits
ok contrast: restoring a snapshot on failure also erases a different edit that succeeded
The conflict policy
On a 409 the store shows the server's current version, records { key, mine, theirs } in conflicts, and drops the user's later queued edits to that item so they cannot overwrite the other person's change on top of the new version. What the user sees next is a product decision: show "this item changed, re-apply your edit?" using the stored mine patches. Automatic merging is safe only when the changed fields do not overlap, and that rule belongs to the API or a clearly named client function, not to scattered UI code.
Trade-offs and pitfalls
- Optimism suits actions that usually succeed. For payments or actions with side effects the user must see, show a pending state until the server answers.
- The server's response is the truth. Writing the response into confirmed data, rather than keeping the optimistic value, is what makes the trimmed title in the first test appear.
- Errors need a visible home.
errorsandconflictsare state the UI must render; a silent rollback looks like the app lost the edit. - Do not key list rows by the real id. A row keyed by
idis unmounted and remounted when the id changes fromnullto100, losing focus and scroll position inside it. - Library fit. If you use a server-state library, check how it lets you apply a change before the request and undo it on error. Recommended: put the pending-list design behind those hooks when overlapping edits are common.
Running the code
npm init -y && npm pkg set type=module
node optimistic_demo.mjs
Run in a node:22 container (Node 22.23.3). No packages are needed. Both files sit in one directory.
Order status updates arrive over a WebSocket while the user is also editing the same orders in the UI. How do you merge incoming events into client state so duplicates, out-of-order messages and reconnects do not corrupt what is on screen?
Sample Answer
Direct answer
Picture an orders screen kept live by a WebSocket (a long-lived connection over which the server pushes messages) while the user is also editing orders. Messages can repeat, arrive late or out of order, and be lost while the connection is down. The answer is to treat the socket as an unreliable stream of facts and merge it with a pure reducer that relies on three pieces of data the server must supply: a per-order version that increases by one for each change, an event id, and (for user edits) an edit id that the client invents. Rules: ignore any event whose version is not newer than the state you hold (that removes duplicates and stale messages); hold back any event that skips a version and ask for a fresh snapshot (that handles out-of-order delivery and gaps); on every reconnect mark all orders for a refetch and let the version check discard the socket's replays; keep the user's unconfirmed edits in a separate layer drawn over the server state, so a server message cannot silently erase them; and keep toasts (momentary) separate from persisted notifications (stored by id).
Terms: an idempotent operation gives the same result when applied twice; optimistic means showing the user's change before the server confirms it; a reducer is a function from (state, action) to a new state with no side effects; a snapshot is a full copy of one order fetched from the REST API (a refetch is simply asking for a new snapshot). A gapless version means the numbers go 1, 2, 3 with none skipped, so a missing number proves an event was missed. An ack (acknowledgement) is the server's reply saying it accepted an edit; a rejection is its reply refusing it. A conflict flag marks a field the user edited and the server changed to a different value meanwhile. A toast is a short pop-up message that disappears by itself. Draining the buffer means applying held-back events one after another for as long as the next needed version is present. A replay is the server resending recent events after a reconnect, some of which the client already has.
State shape
| Slice | Holds | Changed by |
|---|---|---|
orders[id] | { version, fields }, the server's last word | in-order events, snapshots, acks |
buffer[id] | events that arrived ahead of a missing version | early events; drained when the gap closes |
resync[id] | true while a snapshot is needed | gap detected, reconnect |
pending[id][field] | the user's unconfirmed value, its edit id, a conflict flag | local edit, ack, rejection |
toasts | momentary messages, each with a key | events and failures; removed by expiry |
notifications[id] | persisted items, stored by id | notification messages (idempotent) |
A short trace shows how the slices move. Order o1 starts from a snapshot at version 1, then event version 3 arrives before event version 2:
| Step | orders.o1 version | status on screen | buffer.o1 | resync.o1 |
|---|---|---|---|---|
| Snapshot at version 1 | 1 | new | empty | false |
| Event version 3 arrives (version 2 missing) | 1 | new | holds version 3 | true |
| Event version 2 arrives | 3 | shipped | empty | false |
In step 2 the screen still shows version 1 because version 3 cannot be applied without version 2. In step 3, version 2 is applied and the same call drains version 3 from the buffer, so the order jumps to version 3 and resync goes back to false. A snapshot at version 2 arriving in step 2 would close the gap instead, and the buffered version 3 would then drain on top of it.
The screen reads view(state, id): the server fields with the pending values laid over them, plus the lists of fields that are being saved and that are in conflict.
The code
orders.js:
// Pure reducer: (state, action) -> new state. No timers, no sockets, so every case can be replayed in a test.
export const initialState = () => ({
orders: {}, // id -> { version, fields } (what the SERVER says)
buffer: {}, // id -> { [version]: event } (events that arrived ahead of a gap)
resync: {}, // id -> true while a snapshot must be fetched
pending: {}, // id -> { [field]: { value, editId, conflict } } (what the USER typed, unconfirmed)
toasts: [], // transient: { key, text }, removed by TOAST_EXPIRED, never persisted
notifications: {}, // persisted by id: { id, text, read }
});
const push = (toasts, key, text) => (toasts.some((t) => t.key === key) ? toasts : [...toasts, { key, text }]);
// Apply one event that is exactly the next version of its order.
function applyNext(state, ev) {
const cur = state.orders[ev.orderId];
const pend = { ...(state.pending[ev.orderId] ?? {}) };
for (const f of Object.keys(ev.patch)) {
if (pend[f] && pend[f].value !== ev.patch[f]) pend[f] = { ...pend[f], conflict: true }; // keep the user's value on screen, flag it
}
return {
...state,
orders: { ...state.orders, [ev.orderId]: { version: ev.version, fields: { ...cur.fields, ...ev.patch } } },
pending: { ...state.pending, [ev.orderId]: pend },
toasts: push(state.toasts, ev.eventId, `Order ${ev.orderId} updated`),
};
}
// Apply buffered events for as long as the next version is available.
function drain(state, id) {
let s = state;
for (;;) {
const cur = s.orders[id];
const next = cur && s.buffer[id]?.[cur.version + 1];
if (!next) break;
const { [next.version]: _gone, ...rest } = s.buffer[id];
s = applyNext({ ...s, buffer: { ...s.buffer, [id]: rest } }, next);
}
const left = Object.keys(s.buffer[id] ?? {}).length > 0;
return { ...s, resync: { ...s.resync, [id]: left } };
}
function onEvent(state, ev) {
const cur = state.orders[ev.orderId];
if (cur && ev.version <= cur.version) return state; // duplicate or older: ignore
if (cur && ev.version === cur.version + 1) return drain(applyNext(state, ev), ev.orderId);
return { // gap or unknown order: hold it, ask for a snapshot
...state,
buffer: { ...state.buffer, [ev.orderId]: { ...(state.buffer[ev.orderId] ?? {}), [ev.version]: ev } },
resync: { ...state.resync, [ev.orderId]: true },
};
}
export function reducer(state, a) {
switch (a.type) {
case 'EVENT': return onEvent(state, a.event);
case 'SNAPSHOT': {
const { id, version, fields } = a.order;
const cur = state.orders[id];
if (cur && cur.version > version) return state; // a newer state is already here
const kept = Object.fromEntries(Object.entries(state.buffer[id] ?? {}).filter(([v]) => Number(v) > version));
return drain({ ...state, orders: { ...state.orders, [id]: { version, fields } }, buffer: { ...state.buffer, [id]: kept } }, id);
}
case 'RECONNECTED':
return { ...state, resync: Object.fromEntries(Object.keys(state.orders).map((id) => [id, true])) };
case 'LOCAL_EDIT': {
const p = state.pending[a.orderId] ?? {};
return { ...state, pending: { ...state.pending, [a.orderId]: { ...p, [a.field]: { value: a.value, editId: a.editId, conflict: false } } } };
}
case 'EDIT_ACKED': { // the ack carries the resulting event, applied through the same path
let s = a.event ? onEvent(state, a.event) : state;
const p = { ...(s.pending[a.orderId] ?? {}) };
if (p[a.field]?.editId === a.editId) delete p[a.field];
return { ...s, pending: { ...s.pending, [a.orderId]: p } };
}
case 'EDIT_REJECTED': {
const p = { ...(state.pending[a.orderId] ?? {}) };
if (p[a.field]?.editId === a.editId) delete p[a.field]; // roll back: the screen falls back to the server value
return { ...state, pending: { ...state.pending, [a.orderId]: p }, toasts: push(state.toasts, `rej-${a.editId}`, 'Could not save your change') };
}
case 'NOTIFICATION':
if (state.notifications[a.id]) return state; // idempotent by id
return { ...state, notifications: { ...state.notifications, [a.id]: { id: a.id, text: a.text, read: false } }, toasts: push(state.toasts, a.id, a.text) };
case 'TOAST_EXPIRED':
return { ...state, toasts: state.toasts.filter((t) => t.key !== a.key) };
default: return state;
}
}
// What the screen shows: server fields with the user's unconfirmed edits laid over them.
export function view(state, id) {
const o = state.orders[id];
if (!o) return null;
const pend = state.pending[id] ?? {};
const fields = { ...o.fields };
for (const [f, p] of Object.entries(pend)) fields[f] = p.value;
return { ...fields, version: o.version, saving: Object.keys(pend), conflicts: Object.keys(pend).filter((f) => pend[f].conflict) };
}
Reading the reducer:
applyNextapplies an event that is exactly the next version: it lays the event'spatchover the stored fields, marksconflicton any pending field whose value differs from the patch, and adds a toast keyed by the event id (a key already present is not added twice).drainlooks forbuffer[id][version + 1]; when found it removes that event from the buffer and callsapplyNext, then repeats. It stops when the next version is absent and setsresyncto whether anything is still held back.onEventhas three branches: older or equal version (ignore), exactly the next version (apply, then drain), anything else (store in the buffer and setresync).
How each requirement is met:
- Duplicates.
onEventreturns the same state object whenevent.version <= current.version, so the second copy changes nothing and creates no second toast. - Out of order. Version 3 arriving while the order is at version 1 is stored in
bufferandresyncis set; the screen still shows version 1. When version 2 arrives it is applied anddrainimmediately applies the buffered version 3. - Reconnects.
RECONNECTEDmarks every order for refetch. A snapshot replaces the order only if it is not older than what is held, drops buffered events at or below its version, and then drains the rest. Events the socket replays afterwards are older than the state and are ignored by the same version rule. - Optimistic collisions. A user edit goes into
pending, not intoorders. If a server event changes a field the user has pending with a different value, the pending value stays on screen and the field is flaggedconflict, so the UI can say "changed elsewhere". The ack carries the resulting event and goes through the sameonEventpath, then clears the pending entry (matched by edit id, so an older ack cannot clear a newer edit). A rejection deletes the pending entry, so the screen falls back to the server value, and adds one toast "Could not save your change". Conflict policy is "the server decides per field": the user sees their value until the ack, then the server's. - Toast versus notification. A notification is stored by id, so redelivery is a no-op and does not toast again, even after the first toast has expired. The toast has its own key and is removed by
TOAST_EXPIRED(a timer in the UI layer dispatches it), while the notification stays until it is marked read.
Recommendation for the wiring around the reducer (not part of the tested code): open the socket, dispatch RECONNECTED on every successful open, fetch a snapshot for each id in resync through your server-state cache, and send edits over REST with the edit id, dispatching the ack or rejection from the response. This keeps the socket handler thin and the logic testable.
Proving it
The test replays ten scenarios against the reducer and against a "last message wins" version (naive.js) that writes every message straight into state, and asserts that the reducer passes all ten and the naive version fails all ten. Each scenario checks the rule it is named for and also the side effects the prose claims, for example that an ignored duplicate leaves nothing in the buffer and requests no refetch.
naive.js:
// "Last message wins": every message is written straight into state, edits overwrite server data.
export const initialState = () => ({ orders: {}, toasts: [], notifications: [], buffer: {}, resync: {}, pending: {} });
export function reducer(s, a) {
switch (a.type) {
case 'EVENT': {
const e = a.event;
const cur = s.orders[e.orderId] ?? { fields: {} };
return { ...s, orders: { ...s.orders, [e.orderId]: { version: e.version, fields: { ...cur.fields, ...e.patch } } },
toasts: [...s.toasts, { key: e.eventId, text: `Order ${e.orderId} updated` }] };
}
case 'SNAPSHOT': return { ...s, orders: { ...s.orders, [a.order.id]: { version: a.order.version, fields: a.order.fields } } };
case 'LOCAL_EDIT': {
const cur = s.orders[a.orderId];
return { ...s, orders: { ...s.orders, [a.orderId]: { ...cur, fields: { ...cur.fields, [a.field]: a.value } } } };
}
case 'EDIT_ACKED': return a.event ? reducer(s, { type: 'EVENT', event: a.event }) : s;
case 'NOTIFICATION': return { ...s, notifications: [...s.notifications, { id: a.id, text: a.text }], toasts: [...s.toasts, { key: a.id, text: a.text }] };
case 'TOAST_EXPIRED': return { ...s, toasts: s.toasts.filter((t) => t.key !== a.key) };
default: return s; // RECONNECTED and EDIT_REJECTED are not handled
}
}
export function view(s, id) { const o = s.orders[id]; return o ? { ...o.fields, version: o.version, saving: [], conflicts: [] } : null; }
orders.test.js:
import { describe, it, expect } from 'vitest';
import * as good from './orders.js';
import * as naive from './naive.js';
const run = (impl, actions) => actions.reduce(impl.reducer, impl.initialState());
const ev = (version, patch, orderId = 'o1') => ({ type: 'EVENT', event: { eventId: `e${orderId}-${version}`, orderId, version, patch } });
const snap = (version, fields, id = 'o1') => ({ type: 'SNAPSHOT', order: { id, version, fields } });
const nKeys = (x) => Object.keys(x).length;
// Each scenario returns whether the screen ended up correct, plus the facts behind that verdict.
const scenarios = {
'duplicate event shows once': (m) => {
const s = run(m, [snap(1, { status: 'new' }), ev(2, { status: 'paid' }), ev(2, { status: 'paid' })]);
const untouched = Object.keys(s.buffer.o1 ?? {}).length === 0 && !s.resync.o1; // the copy is ignored: nothing buffered, no refetch requested
return { ok: m.view(s, 'o1').status === 'paid' && s.toasts.length === 1 && untouched, status: m.view(s, 'o1').status, toasts: s.toasts.length, untouched };
},
'v3 arrives before v2': (m) => {
const early = run(m, [snap(1, { status: 'new' }), ev(3, { status: 'shipped' })]);
const s = run(m, [snap(1, { status: 'new' }), ev(3, { status: 'shipped' }), ev(2, { status: 'paid' })]);
const holds = m.view(early, 'o1').status === 'new' && early.resync.o1 === true; // the gap is held back and a refresh is requested
return { ok: holds && m.view(s, 'o1').status === 'shipped' && m.view(s, 'o1').version === 3, afterV3Only: m.view(early, 'o1').status, final: m.view(s, 'o1').status };
},
'older event after newer state': (m) => {
const s = run(m, [snap(2, { status: 'paid' }), ev(1, { status: 'new' })]);
return { ok: m.view(s, 'o1').status === 'paid', status: m.view(s, 'o1').status };
},
'reconnect replays events older than current state': (m) => {
const s = run(m, [snap(3, { status: 'paid' }), { type: 'RECONNECTED' }, snap(6, { status: 'delivered' }), ev(7, { status: 'returned' }), ev(4, { status: 'packed' }), ev(5, { status: 'shipped' })]);
const marked = run(m, [snap(3, { status: 'paid' }), { type: 'RECONNECTED' }]).resync.o1 === true; // every known order is marked for refetch
return { ok: marked && m.view(s, 'o1').status === 'returned' && m.view(s, 'o1').version === 7 && !s.resync.o1, status: m.view(s, 'o1').status, version: m.view(s, 'o1').version };
},
'server event hits a field the user is editing': (m) => {
const base = [snap(1, { status: 'new', note: '' }), { type: 'LOCAL_EDIT', orderId: 'o1', field: 'note', value: 'gift', editId: 'x1' }, ev(2, { note: 'rush', status: 'paid' })];
const mid = run(m, base);
const end = run(m, [...base, { type: 'EDIT_ACKED', orderId: 'o1', field: 'note', editId: 'x1', event: { eventId: 'ack', orderId: 'o1', version: 3, patch: { note: 'gift' } } }]);
return { ok: m.view(mid, 'o1').note === 'gift' && m.view(mid, 'o1').status === 'paid' && m.view(mid, 'o1').conflicts.join() === 'note' && m.view(end, 'o1').note === 'gift' && m.view(end, 'o1').saving.length === 0,
noteWhileEditing: m.view(mid, 'o1').note };
},
'save fails: roll back and tell the user once': (m) => {
const s = run(m, [snap(1, { status: 'new' }), { type: 'LOCAL_EDIT', orderId: 'o1', field: 'status', value: 'cancelled', editId: 'x2' }, { type: 'EDIT_REJECTED', orderId: 'o1', field: 'status', editId: 'x2' }]);
return { ok: m.view(s, 'o1').status === 'new' && s.toasts.length === 1, status: m.view(s, 'o1').status, toasts: s.toasts.length };
},
'snapshot closes a gap and clears stale buffer': (m) => {
const a = run(m, [snap(1, { status: 'new' }), ev(3, { status: 'shipped' }), snap(2, { status: 'paid' })]); // v3 then drains on top of the snapshot
const b = run(m, [snap(1, { status: 'new' }), ev(3, { status: 'shipped' }), snap(3, { status: 'shipped' })]); // v3 is now covered by the snapshot
const ok = m.view(a, 'o1').status === 'shipped' && m.view(a, 'o1').version === 3 && !a.resync.o1
&& m.view(b, 'o1').version === 3 && !b.resync.o1 && Object.keys(b.buffer.o1 ?? {}).length === 0;
return { ok, aStatus: m.view(a, 'o1').status, bResync: b.resync.o1 ?? null };
},
'older snapshot does not roll the screen back': (m) => {
const s = run(m, [snap(5, { status: 'delivered' }), snap(4, { status: 'packed' })]);
return { ok: m.view(s, 'o1').status === 'delivered' && m.view(s, 'o1').version === 5, status: m.view(s, 'o1').status };
},
'late ack of an older edit keeps the newer edit': (m) => {
const s = run(m, [snap(1, { note: '' }), { type: 'LOCAL_EDIT', orderId: 'o1', field: 'note', value: 'a', editId: 'x1' },
{ type: 'LOCAL_EDIT', orderId: 'o1', field: 'note', value: 'ab', editId: 'x2' },
{ type: 'EDIT_ACKED', orderId: 'o1', field: 'note', editId: 'x1', event: { eventId: 'ack1', orderId: 'o1', version: 2, patch: { note: 'a' } } }]);
return { ok: m.view(s, 'o1').note === 'ab' && m.view(s, 'o1').saving.join() === 'note', note: m.view(s, 'o1').note };
},
'notification redelivered after its toast expired': (m) => {
const note = { type: 'NOTIFICATION', id: 'n1', text: 'Refund issued' };
const s = run(m, [note, note]);
const after = m.reducer(s, { type: 'TOAST_EXPIRED', key: 'n1' });
const again = m.reducer(after, note); // the server resends it after a reconnect: no second toast
return { ok: nKeys(s.notifications) === 1 && s.toasts.length === 1 && after.toasts.length === 0 && nKeys(after.notifications) === 1 && again.toasts.length === 0 && nKeys(again.notifications) === 1,
persisted: nKeys(s.notifications), toasts: s.toasts.length, toastsAfterRedelivery: again.toasts.length };
},
};
describe('order events merged into client state', () => {
const table = [];
for (const [name, fn] of Object.entries(scenarios)) {
it(name, () => {
const g = fn(good);
const n = fn(naive);
table.push(`${name.padEnd(50)} reducer: ${g.ok ? 'pass' : 'FAIL'} last-message-wins: ${n.ok ? 'pass' : 'FAIL'}`);
expect(g.ok, JSON.stringify(g)).toBe(true);
expect(n.ok, 'the naive version must fail every scenario').toBe(false);
});
}
it('prints the comparison', () => { console.log('\n' + table.join('\n')); });
});
describe('reducer is pure', () => {
it('does not mutate earlier states', () => {
const s1 = run(good, [snap(1, { status: 'new' })]);
const frozen = JSON.stringify(s1);
good.reducer(s1, ev(2, { status: 'paid' }));
expect(JSON.stringify(s1)).toBe(frozen);
});
});
Run in a node:22 container (Node 22.23.3, Vitest 2.1.8, no browser needed because the reducer is pure), the comparison it prints and the result line are:
duplicate event shows once reducer: pass last-message-wins: FAIL
v3 arrives before v2 reducer: pass last-message-wins: FAIL
older event after newer state reducer: pass last-message-wins: FAIL
reconnect replays events older than current state reducer: pass last-message-wins: FAIL
server event hits a field the user is editing reducer: pass last-message-wins: FAIL
save fails: roll back and tell the user once reducer: pass last-message-wins: FAIL
snapshot closes a gap and clears stale buffer reducer: pass last-message-wins: FAIL
older snapshot does not roll the screen back reducer: pass last-message-wins: FAIL
late ack of an older edit keeps the newer edit reducer: pass last-message-wins: FAIL
notification redelivered after its toast expired reducer: pass last-message-wins: FAIL
Tests 12 passed (12)
The twelve tests are the ten scenarios, the comparison printout and a purity check (calling the reducer does not change an earlier state). Deleting any one of these lines from the reducer makes at least one scenario fail: the ev.version <= cur.version ignore, the stale-buffer filter in SNAPSHOT, the older-snapshot guard, the edit-id match in EDIT_ACKED, the RECONNECTED marking, and the state.notifications[a.id] check in NOTIFICATION (without it, a notification redelivered after its toast expired shows a second toast). Each failing row on the right is the technique removed: for instance, with last-message-wins the order in "v3 arrives before v2" ends on the older status, and the local edit disappears when a server event touches the same field.
Trade-offs and pitfalls
- This design depends on the server stamping a gapless per-order version. If it only has timestamps, ignoring "older" events is still possible but gaps cannot be detected; ask the backend for versions or a sequence number.
- A fixed buffer size (and a refetch when it overflows) bounds memory during long outages. Choose the limit from your event rate; it is a tuning value, not a derived one.
- Many orders: the snapshot refetch on reconnect is N requests. Prefer one "changes since" request if the API offers it, and update the cache once.
- Showing the user's value over a conflicting server value is a product choice. For fields where the server must win (status), skip the overlay and show the server value with a message.
Running the code
npm i vitest@2.1.8
Files: orders.js, naive.js, orders.test.js (package.json needs "type": "module")
npx vitest run
Users tap a like button five times quickly on a flaky connection. Implement the click path so the UI responds immediately, a failed request rolls back correctly, and rapid taps do not leave the count wrong.
Sample Answer
Direct answer
Keep three pieces of state instead of one: the confirmed state (the last thing the server acknowledged), the desired state (what the user wants, changed instantly by every tap), and a flag saying whether a request is in flight. Show the desired state immediately (the optimistic update: assuming success and updating the UI before the server answers). Send at most one request at a time, and send the absolute state ("liked = true") rather than a toggle. When a response arrives, replace the guess with the server's answer, and if the user's desired state still differs from it, send one more request. On failure, roll back to the last confirmed state, not to a snapshot taken before the failed tap. This makes five rapid taps cost one request, a failure leave the UI equal to the server, and the displayed count come from the server's reply.
Why the obvious version breaks
The obvious version flips the UI on each click, sends POST /like as a toggle, and on error restores a snapshot of the state from before that click. With rapid taps on a slow connection several requests overlap, each captured a different snapshot, and a toggle applied by the server depends on how many earlier ones succeeded. The program below runs both versions against a fake server that holds every request until the test releases it, so ordering and failures are exact.
Terms used in the code: a snapshot is a copy of state taken at one moment; a round trip is one request plus its response; a state machine is code whose behaviour depends on a small set of named states and the rules for moving between them (here: idle, request in flight, desired differs from confirmed); useRef gives a mutable box (ref.current) that survives re-renders and does not cause one when changed; useCallback returns the same function between renders unless its dependencies change; and a stale closure is a function that keeps using values captured from an earlier render. In the hook, pump is the reconcile loop: it sends a request if the desired state differs from the confirmed one and nothing is in flight, then calls itself again after a success so taps made meanwhile are sent. paint recomputes what the screen shows from the ref.
import { JSDOM } from 'jsdom';
import assert from 'node:assert/strict';
const dom = new JSDOM('<!doctype html><body></body>', { url: 'http://localhost' });
globalThis.window = dom.window; globalThis.document = dom.window.document;
globalThis.IS_REACT_ACT_ENVIRONMENT = true;
const React = (await import('react')).default;
const { render, act, cleanup, fireEvent } = await import('@testing-library/react');
const { useState, useRef, useCallback } = React;
const h = React.createElement;
// ---- fake server: every request is held until the test releases it, so ordering and failures are exact
function makeServer({ liked = false, count = 10 } = {}) {
const s = { liked, count, log: [], held: [] };
const hold = (apply) => new Promise((resolve, reject) => s.held.push({ resolve, reject, apply }));
// idempotent endpoint: PUT sets an absolute state
s.setLike = (want) => { s.log.push(`PUT liked=${want}`);
return hold(() => { if (want !== s.liked) { s.count += want ? 1 : -1; s.liked = want; } return { liked: s.liked, count: s.count }; }); };
// non-idempotent endpoint: POST flips whatever the server has
s.toggle = () => { s.log.push('POST toggle');
return hold(() => { s.liked = !s.liked; s.count += s.liked ? 1 : -1; return { liked: s.liked, count: s.count }; }); };
s.release = async (ok = true) => { const q = s.held.shift();
await act(async () => { if (ok) q.resolve(q.apply()); else q.reject(new Error('network')); await Promise.resolve(); }); };
return s;
}
// ---- the technique: desired state + last confirmed state + at most one request in flight
function useLike(api, initial) {
const ref = useRef({ confirmed: initial, desired: initial.liked, inFlight: false });
const [view, setView] = useState({ liked: initial.liked, count: initial.count, error: null });
const paint = (error = null) => {
const { confirmed, desired } = ref.current;
setView({ liked: desired, count: confirmed.count + (desired ? 1 : 0) - (confirmed.liked ? 1 : 0), error });
};
const pump = useCallback(async () => {
const s = ref.current;
if (s.inFlight || s.desired === s.confirmed.liked) return; // nothing to reconcile, or a request is already out
s.inFlight = true; const sent = s.desired;
try { s.confirmed = await api.setLike(sent); } // the server's answer replaces our guess, count included
catch { s.inFlight = false; s.desired = s.confirmed.liked; paint('Could not save your like'); return; } // back to last CONFIRMED state
s.inFlight = false; paint(); pump(); // taps made while waiting: send the new desired state
}, [api]);
const tap = useCallback(() => { ref.current.desired = !ref.current.desired; paint(); pump(); }, [pump]); // reads the ref, never a stale closure
return { ...view, tap };
}
function Like({ api, initial }) {
const v = useLike(api, initial);
return h('div', null, h('button', { onClick: v.tap }, `${v.liked ? 'Liked' : 'Like'} ${v.count}`), h('span', null, v.error ?? ''));
}
// ---- the naive version: flip locally, toggle on the server, restore a snapshot on failure
function NaiveLike({ api }) {
const [s, setS] = useState({ liked: false, count: 10 });
const click = () => {
const snapshot = s;
setS({ liked: !s.liked, count: s.count + (s.liked ? -1 : 1) });
api.toggle().catch(() => setS(snapshot));
};
return h('button', { onClick: click }, `${s.liked ? 'Liked' : 'Like'} ${s.count}`);
}
const label = (c) => c.querySelector('button').textContent;
const tapN = (c, n) => { for (let i = 0; i < n; i++) fireEvent.click(c.querySelector('button')); };
const start = (server) => render(h(Like, { api: server, initial: { liked: server.liked, count: server.count } })).container;
{ // 1. five rapid taps, request succeeds
const sv = makeServer(); const c = start(sv);
tapN(c, 5);
const instant = label(c);
await sv.release();
console.log('1 five taps : instantly', instant, '| requests', sv.log.join(', '), '| final', label(c), '| server', sv.liked, sv.count);
assert.equal(instant, 'Liked 11'); assert.deepEqual(sv.log, ['PUT liked=true']); assert.equal(label(c), 'Liked 11'); cleanup();
}
{ // 2. four rapid taps: net effect is "not liked", but the first request is already out
const sv = makeServer(); const c = start(sv);
tapN(c, 4);
const instant = label(c);
await sv.release(); await sv.release();
console.log('2 four taps : instantly', instant, '| requests', sv.log.join(', '), '| final', label(c), '| server', sv.liked, sv.count);
assert.equal(instant, 'Like 10'); assert.deepEqual(sv.log, ['PUT liked=true', 'PUT liked=false']);
assert.equal(label(c), 'Like 10'); assert.equal(sv.count, 10); cleanup();
}
{ // 3. failure after three taps: back to the last confirmed state, error shown
const sv = makeServer(); const c = start(sv);
tapN(c, 3);
await sv.release(false);
console.log('3 failure : after rollback', label(c), '|', c.querySelector('span').textContent, '| requests', sv.log.length, '| server', sv.liked, sv.count);
assert.equal(label(c), 'Like 10'); assert.equal(c.querySelector('span').textContent, 'Could not save your like'); assert.equal(sv.log.length, 1); cleanup();
}
{ // 4. another user liked meanwhile: the server's count wins
const sv = makeServer(); const c = start(sv);
tapN(c, 1);
sv.count = 11; // someone else liked while our request was in flight
await sv.release();
console.log('4 server count : optimistic was Liked 11, server says', label(c));
assert.equal(label(c), 'Liked 12'); cleanup();
}
{ // 5. idempotency: absolute PUT twice is harmless, a toggle twice undoes itself
const sv = makeServer();
sv.setLike(true); await sv.release(); sv.setLike(true); await sv.release();
const afterPut = sv.count;
const sv2 = makeServer();
sv2.toggle(); await sv2.release(); sv2.toggle(); await sv2.release();
console.log('5 repeats : PUT liked=true twice ->', afterPut, '| POST toggle twice ->', sv2.count);
assert.equal(afterPut, 11); assert.equal(sv2.count, 10);
}
{ // 6. naive version, five clicks, second request fails
const sv = makeServer(); const c = render(h(NaiveLike, { api: sv })).container;
tapN(c, 5);
for (const ok of [true, false, true, true, true]) await sv.release(ok);
console.log('6 naive : UI', label(c), '| server', sv.liked ? 'liked' : 'not liked', sv.count, '| requests', sv.log.length);
assert.equal(label(c), 'Liked 11'); assert.equal(sv.liked, false); assert.equal(sv.log.length, 5); cleanup();
}
{ // 7. two taps handled before React re-renders (one batch): the second tap must see the first
const sv = makeServer(); const c = start(sv);
const btn = c.querySelector('button');
await act(async () => { btn.click(); btn.click(); });
console.log('7 same batch : label', label(c), '| requests', sv.log.length);
assert.equal(label(c), 'Like 10'); assert.equal(sv.log.length, 1); cleanup();
}
console.log('all assertions passed');
Run in a node:22 container with the packages under "Running the code", it prints:
1 five taps : instantly Liked 11 | requests PUT liked=true | final Liked 11 | server true 11
2 four taps : instantly Like 10 | requests PUT liked=true, PUT liked=false | final Like 10 | server false 10
3 failure : after rollback Like 10 | Could not save your like | requests 1 | server false 10
4 server count : optimistic was Liked 11, server says Liked 12
5 repeats : PUT liked=true twice -> 11 | POST toggle twice -> 10
6 naive : UI Liked 11 | server not liked 10 | requests 5
7 same batch : label Like 10 | requests 1
all assertions passed
Reading the seven cases
-
Five rapid taps: the button shows
Liked 11instantly, before any response. One request was sent (PUT liked=true), because the other four taps only changed the desired state while that request was in flight. The response matched the desired state, so nothing more was sent. -
Four rapid taps: the instant label is
Like 10(net effect of an even number of taps), but the first request was already out, so the hook sent a second one (PUT liked=false) after the first returned. Two requests, final server state equals the screen. A short debounce (waiting until the user has stopped tapping for a fixed delay before sending) before the first send would avoid the second request in this case, at the price of delaying every save. -
Failure: after three taps and a failed request the button returns to
Like 10, an error message is shown, and the pending taps are discarded because the server never confirmed anything. Rolling back to the last confirmed state is correct however many taps happened; a per-tap snapshot is only right if exactly one tap was outstanding. -
Server's count wins: another user liked while the request was in flight. The optimistic count was 11, the server answered 12, and the UI shows
Liked 12. The displayed count isconfirmed.count + (desired ? 1 : 0) - (confirmed.liked ? 1 : 0), so a fresh server value always replaces the local guess. -
Idempotency (repeating a request gives the same result as sending it once):
PUT liked=truesent twice leaves the count at 11, while a toggle sent twice returns to 10. An absolute-state endpoint can be retried after a timeout without risk; a toggle cannot, because the client cannot know whether the first attempt was applied. -
Naive version: five clicks send five toggles, the second request fails, and the screen ends at
Liked 11while the server holdsnot liked 10. The rollback restored a snapshot that no longer described reality, and the UI and server now disagree with no way for the user to see it. -
Two taps in one batch: both clicks are handled before React re-renders (both run inside one
actcall, the way two taps can land in the same frame). The label ends atLike 10and one request (PUT liked=true, sent by the first tap) is out. Each tap flipsref.current.desired, so the second tap sees the first tap's result. A handler that computed!view.likedfrom its render's scope would set the desired state to true twice, and the label would stayLiked 11; that variant passes cases 1 to 6, becausefireEvent.clickre-renders between taps, and fails this case.
Case 6 is the technique removed: the same five taps end in a mismatch, and the assertion on it passes only because the naive code is wrong. The inFlight guard in pump is what keeps case 1 at one request; with the guard deleted (the last command under "Running the code") case 1 fails because the log holds extra PUT liked=true lines: taps 1, 3 and 5 each find the desired state different from the confirmed false, so each sends a request while the earlier one is still out (taps 2 and 4 return the desired state to false and send nothing). Run in the same container, it prints:
1 five taps : instantly Liked 11 | requests PUT liked=true, PUT liked=true, PUT liked=true | final Liked 11 | server true 11
AssertionError [ERR_ASSERTION]: Expected values to be strictly deep-equal:
+ actual - expected
[
'PUT liked=true',
+ 'PUT liked=true',
+ 'PUT liked=true'
]
The values behind case 2 (four taps, then two replies), as confirmed.liked, desired, inFlight, requests sent so far and the button label after each event:
| Event | confirmed.liked | desired | inFlight | Requests sent | Button |
|---|---|---|---|---|---|
| Start | false | false | false | 0 | Like 10 |
| Tap 1 | false | true | true | 1 (PUT liked=true) | Liked 11 |
| Tap 2 | false | false | true | 1 | Like 10 |
| Tap 3 | false | true | true | 1 | Liked 11 |
| Tap 4 | false | false | true | 1 | Like 10 |
| Reply 1 | true | false | true | 2 (PUT liked=false) | Like 10 |
| Reply 2 | false | false | false | 2 | Like 10 |
Taps 2 to 4 only move desired, because inFlight is already true. When the first reply confirms liked=true, the desired false differs again, so pump sends the second request at once; the second reply brings the confirmed state back to false, matching the screen.
Design choices in the hook
- No stale closure. The tap handler flips
ref.current.desired, not a value captured from the render (case 7 fails if it readsview.likedinstead). A callback that readslikedfrom its render's scope sees an old value if two taps are handled before React re-renders; the ref always holds the latest. A functional state update (setX(prev => ...)) solves the same problem for state that is only used in the UI. - Server count is authoritative. The optimistic number is only a prediction; use whatever the response returns.
- Failure indicator. The error is part of the view state and clears on the next successful response; a spinner or "saving" label can be driven by
inFlightin the same way. - Keep it a hook, not a component. The same logic serves a like, a follow, a bookmark or any boolean toggle, and the state machine carries over to a mobile client unchanged: the three fields (confirmed, desired, in-flight) sit on whatever object owns the screen's state, such as a view model, and
pumpbecomes a method guarded by the same flag. Nothing in the logic depends on React. - Reconciling a cache. If likes also appear in a list cache elsewhere on the page, write the confirmed response into that cache once on success, instead of patching it on every tap.
- Conflicts. If another device can change the same record, have the server return the current version with each response and compare it before overwriting; the run above covers the count conflict (case 4) but not concurrent edits of other fields.
Trade-offs and pitfalls
- Serialising requests (one at a time) adds a round trip when the user changes their mind, in exchange for correct final state. Firing all requests in parallel is faster to send but makes the final server state depend on the order the network delivers them.
- Rolling back discards taps the user made after the failed one; telling them (the error message) matters more than trying to replay them silently.
- Optimism suits actions that rarely fail and are cheap to undo; for payments or irreversible actions show a pending state instead.
- This is one fake server with seven hand-ordered scenarios; it demonstrates the logic, not behaviour under real network jitter.
Running the code
npm i react@18.3.1 react-dom@18.3.1 @testing-library/react@16.0.1 @testing-library/dom@10.4.0 jsdom@25.0.1
node like-button.mjs # prints the seven cases and "all assertions passed"
sed 's/s.inFlight || //' like-button.mjs > no-guard.mjs && node no-guard.mjs # guard deleted: case 1 assertion fails (3 requests)
Save the listing as like-button.mjs beside a package.json containing { "type": "module" }. Tested on node:22 (v22.23).
That is every published Frontend Component and State Architecture question for Mobile Developer so far. Browse the other topics in this category, or practice this one interactively.