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.
A parent re-renders every second because of a timer. Which of its children re-render, which do not, and what decides it?
Sample Answer
Direct answer
By default every child the parent returns re-renders on every tick, because "re-render" (React calling the component function again to compute its output) is triggered by the parent's state change and flows down the tree. A child's function is skipped in only two cases: the child is wrapped in React.memo and its props are all shallowly equal to last time (each prop compared one by one with Object.is, without looking inside objects), or the element passed to it is the very same object as last render (the children pattern: a parent receives elements through its children prop, and an element created higher up, in a component that does not re-render, stays the identical object). A child the parent stops returning is unmounted, which is different from being skipped. A child reading a context whose value changed re-renders even inside memo. The deciding factor is referential equality: comparing values by identity (Object.is), so two separately created { color: 'red' } objects are different, while the same variable is equal to itself.
What React does on each tick
- The interval callback calls
setTick. React schedules a render ofTicker, the component that owns the state. Ticker's function runs and returns a new tree of elements (plain objects describing what to render). Everyh(Plain)call in its body creates a fresh element object.- Reconciliation (React comparing the new element tree with the previous one to decide what to update): for each child position React compares element type and
key. Same type and key means "update the existing instance", a different type or key means unmount the old one and mount a new one with fresh state. - For an updated child React then decides whether to call its function. It skips the call when the element is the identical object as last time and nothing inside is pending, or when the component is wrapped in
memoandObject.issays every prop is unchanged (a shallow comparison, one prop at a time). Otherwise the child renders, and the same decision repeats one level down.
React's memo page states the limit: "memo is completely useless if the props passed to your component are always different, such as if you pass an object or a plain function defined during rendering." It also says: "You should only rely on memo as a performance optimization."
Measured per child
The program below mounts a Ticker that owns a one-second setInterval, advances the clock five ticks with Node's mock timers, and counts how many times each child function ran. Each child differs in one thing only: how its props or element are produced. Scaffolding: mock.timers.enable (from node:test) replaces setInterval with a fake clock that moves only when the test calls mock.timers.tick(1000); act(...) from Testing Library runs the code inside it and applies the resulting React updates before returning; hit(name) adds one to a counter each time a component function runs; and process.env.NO_MEMO is an environment switch that swaps memo for a pass-through, so the same file can be run without the technique. Keyed counts inside a useEffect with [], which runs once per mount, so its number counts mounts, not renders.
import { JSDOM } from 'jsdom';
import { mock } from 'node:test';
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 } = await import('@testing-library/react');
const { useState, useEffect, useCallback, createContext, useContext, memo: realMemo } = React;
const h = React.createElement;
const memo = process.env.NO_MEMO ? (c) => c : realMemo; // NO_MEMO=1 removes the technique
const counts = {};
const hit = (name) => { counts[name] = (counts[name] || 0) + 1; };
const TickContext = createContext(0);
const STABLE_STYLE = { color: 'red' };
function Plain() { hit('Plain'); return h('i', null, 'plain'); }
const MemoPrimitive = memo(function MemoPrimitive({ label }) { hit('MemoPrimitive'); return h('i', null, label); });
const MemoInlineObject = memo(function MemoInlineObject({ style }) { hit('MemoInlineObject'); return h('i', { style }, 'x'); });
const MemoStableObject = memo(function MemoStableObject({ style }) { hit('MemoStableObject'); return h('i', { style }, 'x'); });
const MemoInlineFn = memo(function MemoInlineFn({ onPick }) { hit('MemoInlineFn'); return h('i', { onClick: onPick }, 'x'); });
const MemoStableFn = memo(function MemoStableFn({ onPick }) { hit('MemoStableFn'); return h('i', { onClick: onPick }, 'x'); });
const MemoReadsContext = memo(function MemoReadsContext() { const t = useContext(TickContext); hit('MemoReadsContext'); return h('i', null, t); });
function Keyed() { useEffect(() => { hit('Keyed (mounts, key={tick})'); }, []); return h('i', null, 'keyed'); }
function Static() { hit('Static (passed as children)'); return h('i', null, 'static'); }
function Ticker({ children }) { // owns the timer, like the question's parent
const [tick, setTick] = useState(0);
useEffect(() => { const id = setInterval(() => setTick((t) => t + 1), 1000); return () => clearInterval(id); }, []);
const pick = useCallback(() => {}, []);
return h(TickContext.Provider, { value: tick },
h('p', null, 'tick ' + tick),
h(Plain), h(MemoPrimitive, { label: 'a' }),
h(MemoInlineObject, { style: { color: 'red' } }), h(MemoStableObject, { style: STABLE_STYLE }),
h(MemoInlineFn, { onPick: () => {} }), h(MemoStableFn, { onPick: pick }),
h(MemoReadsContext), h(Keyed, { key: tick }), children);
}
function App() { return h(Ticker, null, h(Static)); } // App never re-renders, so the <Static/> element is the same object each time
mock.timers.enable({ apis: ['setInterval'] });
const { container } = render(h(App));
const mountCounts = { ...counts };
for (let i = 0; i < 5; i++) act(() => mock.timers.tick(1000));
console.log('ticks:', container.querySelector('p').textContent);
console.log('renders (mount + 5 ticks):');
for (const k of Object.keys(counts)) console.log(' ', k.padEnd(28), counts[k], '(' + mountCounts[k] + ' on mount)');
assert.equal(container.querySelector('p').textContent, 'tick 5');
assert.equal(counts.Plain, 6);
assert.equal(counts.MemoInlineObject, 6);
assert.equal(counts.MemoInlineFn, 6);
assert.equal(counts.MemoReadsContext, 6);
assert.equal(counts.MemoPrimitive, 1);
assert.equal(counts.MemoStableObject, 1);
assert.equal(counts.MemoStableFn, 1);
assert.equal(counts['Keyed (mounts, key={tick})'], 6);
assert.equal(counts['Static (passed as children)'], 1);
console.log('all assertions passed');
cleanup(); mock.timers.reset();
Run in a node:22 container with the packages listed under "Running the code", it prints:
ticks: tick 5
renders (mount + 5 ticks):
Plain 6 (1 on mount)
MemoPrimitive 1 (1 on mount)
MemoInlineObject 6 (1 on mount)
MemoStableObject 1 (1 on mount)
MemoInlineFn 6 (1 on mount)
MemoStableFn 1 (1 on mount)
MemoReadsContext 6 (1 on mount)
Static (passed as children) 1 (1 on mount)
Keyed (mounts, key={tick}) 6 (1 on mount)
all assertions passed
Reading the table (1 render on mount plus 5 ticks = 6 means "re-rendered every tick"):
Plainand every child that receives a new object or function literal (MemoInlineObject,MemoInlineFn) re-render all 6 times. Wrapping them inmemochanged nothing, because{ color: 'red' }and() => {}written inside the parent are new objects on every render.MemoPrimitive(a string prop),MemoStableObject(a module-level constant) andMemoStableFn(a function wrapped inuseCallback, which returns the same function while its dependency list is unchanged) rendered once.Staticrendered once without anymemo, becauseAppcreated<Static />andAppnever re-renders, soTickerreceives the identicalchildrenelement every tick. Moving state down into a small component, or passing slow parts aschildren, is often a cheaper fix than memoizing.MemoReadsContextre-rendered 6 times despitememo: a context consumer re-renders whenever the provider's value changes, and the provider value here istick.Keyedmounted 6 times (once on mount, then once per tick), becausekey={tick}changes every tick, so React treats each as a different component, discards the old instance with its state and builds a new one. Keys are identity, not just a list concern.
Proving the technique matters
With NO_MEMO=1 the program swaps memo for a pass-through. Run in the same container, the table shows which components change: MemoPrimitive, MemoStableObject and MemoStableFn go from 1 render to 6, while Static stays at 1 because it never relied on memo.
renders (mount + 5 ticks):
Plain 6 (1 on mount)
MemoPrimitive 6 (1 on mount)
MemoInlineObject 6 (1 on mount)
MemoStableObject 6 (1 on mount)
MemoInlineFn 6 (1 on mount)
MemoStableFn 6 (1 on mount)
MemoReadsContext 6 (1 on mount)
Static (passed as children) 1 (1 on mount)
Keyed (mounts, key={tick}) 6 (1 on mount)
AssertionError [ERR_ASSERTION]: Expected values to be strictly equal:
6 !== 1
The failing assertion is the one on MemoPrimitive (counts.MemoPrimitive is 6, expected 1).
Without the useCallback, MemoStableFn would behave like MemoInlineFn; without the constant, MemoStableObject would behave like MemoInlineObject. Those two pairs in the table are that comparison, run side by side.
Trade-offs and pitfalls
- Re-rendering is not the same as touching the DOM. A re-render calls your function and compares the result with the previous one; the browser DOM is only changed where the output differs. Re-render counts matter when the function itself is expensive or the child has many descendants.
- Do not wrap everything in
memoby reflex. It adds a props comparison on every parent render, and it is wasted when any prop is a fresh literal. Profile first (the React DevTools Profiler records each commit, the step where React applies a render's result to the screen, and shows which components rendered in it), then fix the cause: lift the timer down, pass slow children aschildren, or stabilise the one prop that changes identity. - A parent re-render is also not always caused by the timer's own component. If the interval lives in a component near the root, every consumer below pays for it, which is the argument for keeping fast-changing state as close to where it is displayed as possible.
- This run is one small program with five ticks. It shows the rule for these shapes under React 18.3.1; it does not give timing numbers.
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 --disable-warning=ExperimentalWarning rerender.mjs # table + "all assertions passed"
NO_MEMO=1 node --disable-warning=ExperimentalWarning rerender.mjs # fails: 6 !== 1
Save the listing as rerender.mjs in a folder with a package.json containing { "type": "module" }. Tested on node:22 (v22.23).
This component renders {items.length && <List items={items} />} and the page shows a stray 0 whenever the list is empty. Explain why it happens and describe the conditional rendering approaches you would use in JSX and when each is the right choice.
Sample Answer
Direct answer
items.length && <List /> is a JavaScript expression before it is JSX. The && operator returns its left operand when that operand is falsy (a value that counts as false in a condition: false, 0, -0, 0n, '', null, undefined and NaN; everything else is truthy), so with an empty array the expression evaluates to the number 0, and React renders numbers as text. The run below shows that React renders nothing for false, null and undefined, but 0 is a number, so a stray 0 appears. The fix is to make the left side a real boolean (items.length > 0 && ...), or to pick another conditional pattern from the list below.
What React renders for each left operand
The run below renders <div>{v && <b>shown</b>}</div> to a static HTML string (renderToStaticMarkup from react-dom/server turns an element into its markup text without attaching it to a page) for several values of v:
{
"0": "<div>0</div>",
"1": "<div><b>shown</b></div>",
"NaN": "<div>NaN</div>",
"''": "<div></div>",
"false": "<div></div>",
"null": "<div></div>",
"undefined": "<div></div>",
"'0'": "<div><b>shown</b></div>"
}
Three results are worth noticing. 0 and NaN leak into the page. (React 18 also logs a console warning for NaN that starts with "Received NaN for the", but still renders it.) The empty string '' is falsy, is returned by &&, and renders as nothing, so it hides the bug if the left side is a string. And the string '0' is truthy (any non-empty string is), so it takes the right-hand branch. The rule: with &&, the left side must be a boolean, or a value whose falsy cases you are happy to render. A count, a length, a price or an index is a number, so it needs a comparison.
The conditional patterns and when to use each
The code numbers the patterns the same way as the explanation after it: pattern 1 is && (shown as the bug in 1a and the fix in 1b), then 2 ternary, 3 early return, 4 wrapper component, 5 higher-order component, 6 render prop. Patterns 1 to 3 are what most components need; patterns 5 and 6 were the standard ways to share behaviour before hooks arrived in React 16.8, and today a custom hook or a plain wrapper usually does the same job, so they mostly appear in existing code.
export const List = ({ items }) => <ul>{items.map((i) => <li key={i}>{i}</li>)}</ul>;
// 1a. Logical AND on a number (the bug)
export const AndBug = ({ items }) => <div>{items.length && <List items={items} />}</div>;
// 1b. Logical AND on a real boolean
export const AndFixed = ({ items }) => <div>{items.length > 0 && <List items={items} />}</div>;
// 2. Ternary: two different outcomes
export const Ternary = ({ items }) => (
<div>{items.length > 0 ? <List items={items} /> : <p>Nothing here yet</p>}</div>
);
// 3. Early return: the whole component bails out
export function EarlyReturn({ items }) {
if (items.length === 0) return <p>Nothing here yet</p>;
return <List items={items} />;
}
// 4. Wrapper component that gates its children
export const When = ({ if: cond, fallback = null, children }) => (cond ? children : fallback);
export const Gated = ({ items }) => (
<When if={items.length > 0} fallback={<p>Nothing here yet</p>}><List items={items} /></When>
);
// 5. Higher-order component (a function that takes a component and returns a gated one)
export const hideWhenEmpty = (Component) => (props) => (props.items.length > 0 ? <Component {...props} /> : null);
export const HiddenList = hideWhenEmpty(List);
// 6. Render prop: the data component decides, the caller supplies the markup
export const WithItems = ({ items, children }) => (items.length > 0 ? children(items) : null);
cond && <X />(with a booleancond): the shortest form, right when "nothing" is the correct empty output. Useitems.length > 0,Boolean(x)or!!x(both turn any value intotrueorfalse). The operator short-circuits: when the left side is falsy, the right side is never evaluated.- Ternary
cond ? <A /> : <B />: right when both outcomes render something, such as the list or an empty-state message. It is also safe against the0problem because the result is whichever branch you wrote. Avoid nesting ternaries; extract a component. - Early return (
if (...) return <Empty />): right when the whole component has nothing to show, because it keeps the main path unindented. Put it after all hook calls. - A gating wrapper component (
<When if={...} fallback={...}>): right when several places repeat the same condition and fallback. This is the plain form of what a higher-order component or a render prop does. - A higher-order component (HOC) such as
hideWhenEmpty(List): a function that takes a component and returns a gated one. It suits behaviour shared across many components, but it hides the condition inside a wrapper, so prefer a plain wrapper or a hook unless many components need the same gate. - A render prop (
<WithItems>{(items) => ...}</WithItems>): a component receives a function aschildrenand calls it only when there is data; right when the data owner decides when to render and the caller owns the markup.
Proof
import { renderToStaticMarkup } from 'react-dom/server';
import { render } from '@testing-library/react';
import { AndBug, AndFixed, Ternary, EarlyReturn, Gated, WithItems, HiddenList, List } from './conditional.jsx';
const html = (el) => renderToStaticMarkup(el);
const filled = ['a', 'b'];
test('what each value of the left operand renders when it is the whole && expression', () => {
const row = (v) => html(<div>{v && <b>shown</b>}</div>);
const got = {
'0': row(0), 'NaN': row(NaN), "''": row(''), 'false': row(false),
'null': row(null), 'undefined': row(undefined), '1': row(1), "'0'": row('0'),
};
console.log(JSON.stringify(got, null, 1));
expect(got['0']).toBe('<div>0</div>');
expect(got['NaN']).toBe('<div>NaN</div>');
expect(got["''"]).toBe('<div></div>');
expect(got['false']).toBe('<div></div>');
expect(got['null']).toBe('<div></div>');
expect(got['undefined']).toBe('<div></div>');
expect(got['1']).toBe('<div><b>shown</b></div>');
expect(got["'0'"]).toBe('<div><b>shown</b></div>');
});
test('the bug: an empty array renders a literal 0', () => {
expect(html(<AndBug items={[]} />)).toBe('<div>0</div>');
expect(html(<AndBug items={filled} />)).toBe('<div><ul><li>a</li><li>b</li></ul></div>');
});
test('every fix renders no stray 0 and the same list when there are items', () => {
const list = '<ul><li>a</li><li>b</li></ul>';
expect(html(<AndFixed items={[]} />)).toBe('<div></div>');
expect(html(<AndFixed items={filled} />)).toBe(`<div>${list}</div>`);
expect(html(<Ternary items={[]} />)).toBe('<div><p>Nothing here yet</p></div>');
expect(html(<Ternary items={filled} />)).toBe(`<div>${list}</div>`);
expect(html(<EarlyReturn items={[]} />)).toBe('<p>Nothing here yet</p>');
expect(html(<EarlyReturn items={filled} />)).toBe(list);
expect(html(<Gated items={[]} />)).toBe('<p>Nothing here yet</p>');
expect(html(<Gated items={filled} />)).toBe(list);
expect(html(<HiddenList items={[]} />)).toBe('');
expect(html(<HiddenList items={filled} />)).toBe(list);
expect(html(<WithItems items={[]}>{(i) => <List items={i} />}</WithItems>)).toBe('');
expect(html(<WithItems items={filled}>{(i) => <List items={i} />}</WithItems>)).toBe(list);
});
test('the && version also updates correctly in the DOM when the list empties', () => {
const { container, rerender } = render(<AndBug items={filled} />);
expect(container.textContent).toBe('ab');
rerender(<AndBug items={[]} />);
expect(container.textContent).toBe('0');
});
test('&& short-circuits: the right-hand side is not evaluated when the left is falsy', () => {
let evaluated = 0;
const heavy = () => { evaluated += 1; return <b>x</b>; };
html(<div>{false && heavy()}</div>);
expect(evaluated).toBe(0);
html(<div>{true && heavy()}</div>);
expect(evaluated).toBe(1);
});
Run with the setup below and the command npx vitest run cond --reporter=verbose 2>&1 | grep -E '^ (✓|×)|Tests |Assertion' (the grep keeps only the result lines; the first test also prints the JSON table shown earlier), the result lines are:
✓ cond/conditional.test.jsx > what each value of the left operand renders when it is the whole && expression
✓ cond/conditional.test.jsx > the bug: an empty array renders a literal 0
✓ cond/conditional.test.jsx > every fix renders no stray 0 and the same list when there are items
✓ cond/conditional.test.jsx > the && version also updates correctly in the DOM when the list empties
✓ cond/conditional.test.jsx > && short-circuits: the right-hand side is not evaluated when the left is falsy
Tests 5 passed (5)
The tests assert the exact markup for the bug (<div>0</div>), for each fix with an empty and a non-empty array, for the DOM update when a list empties, and for && short-circuiting. A mutation check temporarily breaks the real code and confirms a test notices: changing the fixed component back to items.length && (sed -i 's/items.length > 0 \&\& <List/items.length \&\& <List/' cond/conditional.jsx) fails the fix test:
✓ cond/conditional.test.jsx > what each value of the left operand renders when it is the whole && expression
✓ cond/conditional.test.jsx > the bug: an empty array renders a literal 0
× cond/conditional.test.jsx > every fix renders no stray 0 and the same list when there are items
✓ cond/conditional.test.jsx > the && version also updates correctly in the DOM when the list empties
✓ cond/conditional.test.jsx > && short-circuits: the right-hand side is not evaluated when the left is falsy
⎯⎯⎯⎯⎯⎯⎯ Failed Tests 1 ⎯⎯⎯⎯⎯⎯⎯
AssertionError: expected '<div>0</div>' to be '<div></div>' // Object.is equality
Tests 1 failed | 4 passed (5)
Pitfalls
- Rendering
0is sometimes wanted. A cart count of 0 may need to show "0 items". Then use a ternary and write the zero case on purpose. - Missing data. If
itemscan beundefinedwhile loading,items.lengththrows. Use a loading branch first (if (!items) return <Spinner />) rather thanitems?.length, which turns "not loaded" into "empty" and flashes the wrong message. - Hooks order. An early return placed before a hook call changes the number of hooks between renders. Put early returns after all hooks.
- Nested
&&chains read as logic puzzles; name the condition (const hasResults = items.length > 0) first.
Running the code
npm init -y && npm pkg set type=module # files go in demo/cond/
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 vitest@2.1.4
# vitest.config.js:
# import { defineConfig } from 'vitest/config';
# export default defineConfig({ esbuild: { jsx: 'automatic' }, test: { environment: 'jsdom', globals: true } });
npx vitest run cond --reporter=verbose 2>&1 | grep -E '^ (✓|×)|Tests |Assertion'
Run in a node:22 container (Node 22.23.3).
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.
A teammate asks when something should be a prop and when it should be state. How do you explain the difference, and how do you decide in a concrete example such as a product card with a quantity stepper?
Sample Answer
Direct answer
Props are the inputs a parent passes to a component; the component reads them and never changes them. State is data a component remembers between renders and updates itself, usually in response to the user. A render is one call of the component's function: React runs it to work out the markup for the current props and state, and runs it again (a re-render) whenever the component's own state changes or its parent re-renders. React normally re-renders a component whenever its parent re-renders, even when the props are identical; wrapping the component in React.memo opts out when the props are unchanged. Without state, a function would forget everything between those calls. To decide which a value is, ask three questions in order: can it be computed from props or other state (then it is neither, just a variable)? Is it decided by the parent (then it is a prop)? Does it change because of something that happens inside this component and must survive re-renders (then it is state)? In a product card with a quantity stepper, the name, price and stock are props, the quantity is state, and the total is computed.
How to explain it to a teammate
An analogy that holds up: props are the arguments to a function, state is a variable the function remembers between calls. A parent passes <ProductCard name="Mug" priceCents={1250} stock={5} />; the card cannot reassign name, it can only ask the parent for a different one through a callback prop like onAdd. If the card needed a different name, the parent would render it again with a new prop. Props are read-only because data flows one way, downward: if children could rewrite what their parent gave them, any component could change any other's inputs and nobody could trace why a value changed.
Deciding for the product card
| Value | Source | Verdict |
|---|---|---|
name, priceCents, stock | Parent / data layer | Props |
onAdd | Parent decides what "add" does | Callback prop |
quantity | User clicks the stepper; nothing else computes it | State |
totalCents | quantity * priceCents | Derived: compute in render, store nowhere |
| Stepper's displayed number and limits | Card passes them | Props of Stepper (it has no state) |
Implementation
import { useState } from 'react';
// Stepper: no state of its own. The number it shows and the limits are props.
export function Stepper({ value, min, max, onChange }) {
return (
<div>
<button aria-label="decrease" disabled={value <= min} onClick={() => onChange(value - 1)}>-</button>
<output aria-label="quantity">{value}</output>
<button aria-label="increase" disabled={value >= max} onClick={() => onChange(value + 1)}>+</button>
</div>
);
}
// ProductCard: name, priceCents, stock and onAdd come from the parent (props).
// quantity changes in response to the user and nothing else computes it, so it is state.
// total is computed from props + state on each render, so it is neither.
export function ProductCard({ name, priceCents, stock, onAdd }) {
const [quantity, setQuantity] = useState(1);
const totalCents = quantity * priceCents;
return (
<section>
<h2>{name}</h2>
<Stepper value={quantity} min={1} max={stock} onChange={setQuantity} />
<p data-testid="total">{(totalCents / 100).toFixed(2)}</p>
<button onClick={() => onAdd({ name, quantity })}>Add to cart</button>
</section>
);
}
The stepper has no state: it shows the value it is given and calls onChange. The card keeps quantity and computes totalCents on each render.
Proof
The control stores the total in state instead:
import { useState } from 'react';
import { Stepper } from './ProductCard.jsx';
// Negative control: the total is copied into state when the quantity changes.
export function StoredTotalCard({ name, priceCents, stock }) {
const [quantity, setQuantity] = useState(1);
const [totalCents, setTotalCents] = useState(priceCents);
return (
<section>
<h2>{name}</h2>
<Stepper value={quantity} min={1} max={stock} onChange={(q) => { setQuantity(q); setTotalCents(q * priceCents); }} />
<p data-testid="total">{(totalCents / 100).toFixed(2)}</p>
</section>
);
}
import { render, screen, fireEvent } from '@testing-library/react';
import { ProductCard } from './ProductCard.jsx';
import { StoredTotalCard } from './StoredTotalCard.jsx';
const total = () => screen.getByTestId('total').textContent;
const qty = () => screen.getByLabelText('quantity').textContent;
const inc = () => fireEvent.click(screen.getByLabelText('increase'));
test('quantity is state: it changes on click and is clamped by the stock prop', () => {
render(<ProductCard name="Mug" priceCents={1250} stock={3} onAdd={() => {}} />);
expect(qty()).toBe('1');
inc(); inc();
expect(qty()).toBe('3');
expect(screen.getByLabelText('increase').disabled).toBe(true);
fireEvent.click(screen.getByLabelText('decrease'));
expect(qty()).toBe('2');
});
test('total is derived: it follows the price prop without any syncing code', () => {
const { rerender } = render(<ProductCard name="Mug" priceCents={1250} stock={5} onAdd={() => {}} />);
inc(); inc();
expect(total()).toBe('37.50');
rerender(<ProductCard name="Mug" priceCents={1000} stock={5} onAdd={() => {}} />); // parent changes a prop
expect(total()).toBe('30.00');
expect(qty()).toBe('3'); // state survives a prop change
});
test('negative control: a total stored in state goes stale when the price prop changes', () => {
const { rerender } = render(<StoredTotalCard name="Mug" priceCents={1250} stock={5} />);
inc(); inc();
rerender(<StoredTotalCard name="Mug" priceCents={1000} stock={5} />);
expect(total()).toBe('37.50'); // 3 x 10.00 should be 30.00
});
test('the callback prop reports state upward; the parent never reaches in', () => {
const added = [];
render(<ProductCard name="Mug" priceCents={1250} stock={5} onAdd={(x) => added.push(x)} />);
inc();
fireEvent.click(screen.getByText('Add to cart'));
expect(added).toEqual([{ name: 'Mug', quantity: 2 }]);
});
test('props are read-only: this React 18.3.1 development build freezes the props object', () => {
let seen;
const Probe = (props) => { seen = props; return null; };
render(<Probe name="Mug" />);
expect(Object.isFrozen(seen)).toBe(true);
expect(() => { seen.name = 'Cup'; }).toThrow(TypeError);
expect(seen.name).toBe('Mug');
});
Run with the setup below and the command npx vitest run propstate --reporter=verbose 2>&1 | grep -E '^ (✓|×)|Tests |Assertion' (the grep keeps only the result lines), the output is:
✓ propstate/propstate.test.jsx > quantity is state: it changes on click and is clamped by the stock prop
✓ propstate/propstate.test.jsx > total is derived: it follows the price prop without any syncing code
✓ propstate/propstate.test.jsx > negative control: a total stored in state goes stale when the price prop changes
✓ propstate/propstate.test.jsx > the callback prop reports state upward; the parent never reaches in
✓ propstate/propstate.test.jsx > props are read-only: this React 18.3.1 development build freezes the props object
Tests 5 passed (5)
The tests show: quantity changes on click and is capped by the stock prop; when the parent re-renders the card with a new priceCents, the total follows (3 x 10.00 is 30.00) with the quantity kept; the stored-total control still shows 37.50 after the same price change; onAdd receives { name, quantity }; and in this React 18.3.1 development build the props object is frozen, so assigning to a prop throws a TypeError. A mutation check temporarily breaks the real code and confirms a test notices. Storing the total in the real card's state (sed -i 's/const totalCents = quantity \* priceCents;/const [totalCents, setTotalCents] = useState(priceCents);/;s/onChange={setQuantity}/onChange={(q) => { setQuantity(q); setTotalCents(q * priceCents); }}/' propstate/ProductCard.jsx) fails the derived-total test, because the total stays at 37.50 after the price prop drops to 10.00:
✓ propstate/propstate.test.jsx > quantity is state: it changes on click and is clamped by the stock prop
× propstate/propstate.test.jsx > total is derived: it follows the price prop without any syncing code
✓ propstate/propstate.test.jsx > negative control: a total stored in state goes stale when the price prop changes
✓ propstate/propstate.test.jsx > the callback prop reports state upward; the parent never reaches in
✓ propstate/propstate.test.jsx > props are read-only: this React 18.3.1 development build freezes the props object
⎯⎯⎯⎯⎯⎯⎯ Failed Tests 1 ⎯⎯⎯⎯⎯⎯⎯
AssertionError: expected '37.50' to be '30.00' // Object.is equality
Tests 1 failed | 4 passed (5)
When state has to move
If something else on the page also needs the quantity (a cart summary, a sticky "buy" bar), keep it out of the card: move the state to the closest component that contains both users, and pass it down as a quantity prop with an onQuantityChange callback. That is "lifting state up", and it is the same shape the Stepper already has: a controlled component, one whose current value comes in as a prop and whose changes are reported through a callback instead of being kept inside. Doing it before a second reader exists adds props without a benefit.
Pitfalls
- Copying a prop into state (
useState(props.price)) creates a second source of truth that stops following the prop after the first render, which is what the stored-total control shows. - State that can be computed (totals, filtered lists, "is empty") is the most common over-use of state; compute it in render.
- Mutating props or state objects in place hides changes from React and breaks one-way flow; the frozen props above are the guard rail for props, state needs the discipline of making new objects.
- State that should be in the URL (selected size, sort order) belongs in the router if links must reproduce it.
Running the code
# files in demo/propstate/: ProductCard.jsx (Implementation block), StoredTotalCard.jsx (first Proof block), propstate.test.jsx (second Proof block)
npm init -y && npm pkg set type=module
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 vitest@2.1.4
# vitest.config.js:
# import { defineConfig } from 'vitest/config';
# export default defineConfig({ esbuild: { jsx: 'automatic' }, test: { environment: 'jsdom', globals: true } });
npx vitest run propstate --reporter=verbose 2>&1 | grep -E '^ (✓|×)|Tests |Assertion'
Run in a node:22 container (Node 22.23.3).
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).
Unlock Full Question Bank
Get access to all Frontend Component and State Architecture interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.