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 React codebase has grown from 5 to 60 engineers and the components folder is a flat dump of 400 files. How would you reorganize it, and what rules would you set so new code lands in the right place without a gatekeeper?
Sample Answer
Direct answer
Reorganize by feature, not by file type (an alias such as @/ is a short import prefix that the bundler and editor map to src/, so @/features/billing means src/features/billing): one folder per product area that holds its components, hooks, API calls, tests and styles, a thin shared/ layer for genuinely cross-cutting pieces, and an app/ layer that wires routes together. Then make the rules mechanical: a lint rule rejects imports that cross a feature's boundary except through its public index file, so the folder structure is enforced by the pull-request check rather than by a reviewer who has to remember it. Migrate feature by feature with history-preserving moves, never in one pull request.
Target layout
src/
app/ routes, providers, bootstrapping (may import any feature's index)
features/
billing/
index.js the ONLY file other code may import from this feature
BillingPage.jsx
InvoiceTable.jsx / InvoiceTable.test.jsx / InvoiceTable.css (colocated)
api.js this feature's requests (no JSX)
useInvoices.js this feature's data hook
internal/ helpers nobody else may import
orders/ ...
shared/
ui/ domain-free display pieces with no product knowledge (Button, Modal)
lib/ utilities and the HTTP client
Why this shape:
- A folder answers "where does this go?" A billing invoice table goes in
features/billing. Only code with no product knowledge goes inshared/. - Colocation. Tests, styles and stories (Storybook files: small examples that render one component in each of its states in a catalogue) sit beside the component they describe, so deleting or moving a component moves everything with it.
- API services and hooks separated from views.
api.jsholds request functions,useInvoices.jsholds the data hook,.jsxfiles render. Views never callfetch. - One public door. Other code imports
@/features/billing, never@/features/billing/internal/.... That is what lets a feature be rewritten without grepping the whole codebase. - A small app is the counter-case. With a few dozen files and one team, a flat folder per type is fine and cheaper; the feature layout pays off when many people change different areas at once, which is the 60-engineer situation.
Placement rules
- A feature imports other features only through their
indexfile. shared/imports nothing fromfeatures/orapp/.- Code used by two features moves to
shared/only after the second real use; until then it stays in the first feature (copy before you abstract). - A file's tests and styles live in the same folder.
- Inside a feature, import siblings with relative paths. Inside the whole app, use the alias only for crossing a boundary.
- Only a feature's
indexfile may be a barrel. A barrel is anindexfile that re-exports many modules; one in every folder hides which module is really used and makes circular imports easy to create.
Rules 1 and 2 are enforced by ESLint's no-restricted-imports option. In ESLint's flat config (eslint.config.js) the exported array is a list of config blocks; each block applies its rules only to the files matched by its files globs. A patterns entry is a gitignore-style glob on the import path, where * matches one path segment: @/features/*/* therefore matches @/features/billing/internal/x.js (a segment inside a feature) but not @/features/billing (the feature's public door). The config and a tiny sample tree that breaks both rules:
// Boundary rules for the feature-folder layout. Imports use the "@/" alias for src/.
const toInternals = {
group: ['@/features/*/*'],
message: 'Import another feature only through its index file (@/features/<name>).',
};
const intoFeatures = {
group: ['@/features/**', '@/app/**'],
message: 'shared/ is the bottom layer: it must not import features or app code.',
};
export default [
{ files: ['src/**/*.js'], languageOptions: { ecmaVersion: 2022, sourceType: 'module' } },
// app and every feature: may import other features, but only their public index
{ files: ['src/app/**', 'src/features/**'], rules: { 'no-restricted-imports': ['error', { patterns: [toInternals] }] } },
// shared: may import nothing above it
{ files: ['src/shared/**'], rules: { 'no-restricted-imports': ['error', { patterns: [intoFeatures] }] } },
];
mkdir -p src/app src/features/billing/internal src/features/orders/internal src/shared/ui
cat > src/app/routes.js <<'EOF'
import { BillingPage } from '@/features/billing';
import { OrdersPage } from '@/features/orders';
export const routes = [BillingPage, OrdersPage];
EOF
cat > src/features/billing/index.js <<'EOF'
export { BillingPage } from './BillingPage.js';
EOF
cat > src/features/billing/BillingPage.js <<'EOF'
import { Button } from '@/shared/ui/Button.js';
import { OrdersPage } from '@/features/orders';
import { invoiceTotal } from './internal/invoiceTotal.js';
import { OrderRow } from '@/features/orders/internal/OrderRow.js';
export const BillingPage = { Button, OrdersPage, invoiceTotal, OrderRow };
EOF
cat > src/features/billing/internal/invoiceTotal.js <<'EOF'
export const invoiceTotal = (lines) => lines.reduce((a, l) => a + l.cents, 0);
EOF
cat > src/features/orders/index.js <<'EOF'
export { OrdersPage } from './OrdersPage.js';
EOF
cat > src/features/orders/OrdersPage.js <<'EOF'
import { OrderRow } from './internal/OrderRow.js';
export const OrdersPage = { OrderRow };
EOF
cat > src/features/orders/internal/OrderRow.js <<'EOF'
export const OrderRow = () => null;
EOF
cat > src/shared/ui/Button.js <<'EOF'
import { BillingPage } from '@/features/billing';
export const Button = { BillingPage };
EOF
Which file breaks which rule:
| File | Offending line | Rule broken |
|---|---|---|
src/features/billing/BillingPage.js | line 4, import { OrderRow } from '@/features/orders/internal/OrderRow.js' | rule 1 (deep import into another feature) |
src/shared/ui/Button.js | line 1, import { BillingPage } from '@/features/billing' | rule 2 (shared/ importing a feature) |
src/features/billing/BillingPage.js | line 2, import { OrdersPage } from '@/features/orders' | none (public door) |
Running npx eslint src on that tree prints:
/w/src/features/billing/BillingPage.js
4:1 error '@/features/orders/internal/OrderRow.js' import is restricted from being used by a pattern. Import another feature only through its index file (@/features/<name>) no-restricted-imports
/w/src/shared/ui/Button.js
1:1 error '@/features/billing' import is restricted from being used by a pattern. shared/ is the bottom layer: it must not import features or app code no-restricted-imports
✖ 2 problems (2 errors, 0 warnings)
The legal imports in the same tree (@/features/orders through its index, @/shared/ui/Button.js from a feature, relative imports inside a feature) are not reported. To show that the errors come from the two rule blocks, a second config keeps only the parser block:
export default [
{ files: ['src/**/*.js'], languageOptions: { ecmaVersion: 2022, sourceType: 'module' } },
];
Saved as eslint.norules.config.js, npx eslint -c eslint.norules.config.js src; echo "exit code: $?" prints:
exit code: 0
while npx eslint src >/dev/null; echo "exit code: $?" with the real config prints exit code: 1.
The alias patterns only see alias imports. Relative paths slip past them: with src/features/billing/rel.js containing import { OrderRow } from '../orders/internal/OrderRow.js' and src/shared/ui/rel2.js containing import { BillingPage } from '../../features/billing/BillingPage.js', npx eslint on those two files with the config above prints nothing and exits 0. Two regex patterns (supported by no-restricted-imports next to group) close the relative forms that can be recognised from the text alone:
const relToInternals = {
regex: '^(\\.\\./)+[^./][^/]*/internal/', // ../orders/internal/x.js, but not ../internal/x.js inside a feature
message: 'Import another feature only through its index file (@/features/<name>).',
};
const relIntoFeatures = {
regex: '^(\\.\\./)+(features|app)/', // ../../features/billing/x.js from shared/
message: 'shared/ is the bottom layer: it must not import features or app code.',
};
// add relToInternals to the patterns of the app/features block and relIntoFeatures to the shared block
With both added, the same tree reports four errors (the two original ones plus rel.js and rel2.js), while ../internal/invoiceTotal.js and ../../internal/invoiceTotal.js written inside a feature's own subfolders are not reported. A relative import from one feature into another feature's non-internal file (../orders/OrdersPage.js) cannot be told apart from a legitimate import inside the feature by text alone, so that case still depends on rule 5 and review, or on a rule that compares resolved file paths.
Because the pattern @/features/*/* rejects every deep alias import, a feature must import its own internals with relative paths (rule 5), which also keeps the alias for boundary crossings only. Rules 3, 4 and 6 are not covered by this config; they need review habits, a file-generator template, or additional lint plugins.
Migration without a freeze
- Agree the target tree and add the lint config in warning mode, so nothing breaks on day one.
- Move one feature per pull request with
git mv(history follows the file), rewrite its imports with the editor's rename-refactor or a codemod (a script that rewrites source code mechanically), and let its team own the pull request. - New code goes in the new layout immediately; old code moves when its feature is next touched or when its owner schedules it.
- When a feature is moved, switch the rules to
errorfor that folder only, so finished areas cannot regress. - Add a code-owners entry per feature folder (a
CODEOWNERSfile on GitHub or GitLab maps path patterns to people or teams, who are then requested as reviewers automatically) so reviews route to the people who know the area.
Trade-offs and pitfalls
- Wrong boundaries are expensive. Features split by team org chart instead of by user-visible area move every reorganization. Start from routes and navigation, which users already see.
shared/becomes the new flat dump. The "second real use" rule and a reviewer question ("does this know anything about billing?") are the defence.- Cycles between features. If billing needs orders and orders needs billing, the boundary is wrong or a third module is missing; merge them or extract the shared part.
- Tooling cost. Aliases (
@/) must be configured in the bundler, test runner and editor, or imports break in one of the three.
Running the code
mkdir layout && cd layout && npm init -y && npm pkg set type=module
npm i eslint@9.14.0
# save the config above as eslint.config.js and the script above as setup.sh
sh setup.sh && npx eslint src
# save the parser-only config as eslint.norules.config.js
npx eslint -c eslint.norules.config.js src; echo "exit code: $?"
Run in a node:22 container (Node 22.23.3, ESLint 9.14.0).
Build a small global store in React for a shopping cart (add, remove, clear) that any component can read and update, so that a component showing only the item count does not re-render when an unrelated field changes. Show the code.
Sample Answer
Direct answer
Keep the cart in a small store that lives outside React's render cycle (a plain object with getState, dispatch and subscribe: dispatch sends it an action, a plain object such as { type: 'add', id: 'p1' } describing what happened, and a reducer, a function (state, action) => nextState, computes the new state), put only the store object in context, and let each component subscribe to just the slice it needs (a slice is one part of the state, such as the item count or the banner text) with useSyncExternalStore. A component that returns selectCount(state) is re-rendered only when that number changes, so editing an unrelated field such as a banner message never touches it. If you instead put the whole state object in a context value, every consumer re-renders on every change, which the last test below demonstrates.
How it works
- The store holds
state, applies a reducer ondispatch, and calls its listeners only when the reducer returned a different object. A no-op action (clearing an already empty cart) therefore notifies nobody. - The context holds the store itself. The store object never changes identity, so the provider never forces anything to re-render. Context here is a way to find the store without prop drilling (passing it down through every component), not the channel that carries updates.
useSyncExternalStore(subscribe, getSnapshot)is React's hook for reading an external store. react.dev says: "Thesubscribefunction should subscribe to the store and return a function that unsubscribes." and "While the store has not changed, repeated calls togetSnapshotmust return the same value." (https://react.dev/reference/react/useSyncExternalStore). OurgetSnapshotisselector(store.getState()). React compares each result with the previous one usingObject.isand re-renders only if it differs. A selector that returns a number or string is stable between unrelated changes.
What the reducer does to a small state, step by step. The test dispatches setBanner with 'Sale' first, so every row below carries that banner:
| Action | State before | State after | Listeners notified? |
|---|---|---|---|
add p1 | { items: [], banner: 'Sale' } | { items: [{ id: 'p1', name: 'Pen', qty: 1 }], banner: 'Sale' } | yes (new object) |
add p1 again | the state above | the p1 line becomes qty: 2 (map copies the list and the changed line) | yes |
add p2 | p1 with qty: 2 | p1 (qty: 2) plus { id: 'p2', name: 'Ink', qty: 1 }, so selectCount is 3 | yes |
remove p1 | both lines | only p2, so selectCount is 1 | yes |
remove nope | only p2 | the same object is returned (some found nothing) | no |
clear | only p2 | { items: [], banner: 'Sale' } (new object, qty total 0) | yes |
clear again | empty cart | the same object is returned | no |
The identity check that decides "notified?" is Object.is(next, state) in dispatch: when the reducer hands back the very same object, the two are identical and the store returns early; any new object, even with equal contents, counts as a change.
The code
// cartStore.jsx
import { createContext, useContext, useSyncExternalStore } from 'react';
export const initialCart = { items: [], banner: '' };
export function cartReducer(state, action) {
switch (action.type) {
case 'add': {
const found = state.items.find((i) => i.id === action.id);
const items = found
? state.items.map((i) => (i.id === action.id ? { ...i, qty: i.qty + 1 } : i))
: [...state.items, { id: action.id, name: action.name, qty: 1 }];
return { ...state, items };
}
case 'remove':
return state.items.some((i) => i.id === action.id)
? { ...state, items: state.items.filter((i) => i.id !== action.id) }
: state;
case 'clear':
return state.items.length === 0 ? state : { ...state, items: [] };
case 'setBanner':
return state.banner === action.text ? state : { ...state, banner: action.text };
default:
return state;
}
}
export function createStore(reducer, initialState) {
let state = initialState;
const listeners = new Set();
return {
getState: () => state,
dispatch(action) {
const next = reducer(state, action);
if (Object.is(next, state)) return; // nothing changed: nobody is notified
state = next;
listeners.forEach((l) => l());
},
subscribe(listener) {
listeners.add(listener);
return () => listeners.delete(listener);
},
};
}
const StoreContext = createContext(null);
export function CartProvider({ store, children }) {
// The context value is the store object itself. It never changes, so the
// provider never forces consumers to re-render.
return <StoreContext.Provider value={store}>{children}</StoreContext.Provider>;
}
export function useCartSelector(selector) {
const store = useContext(StoreContext);
return useSyncExternalStore(store.subscribe, () => selector(store.getState()));
}
export function useCartDispatch() {
return useContext(StoreContext).dispatch;
}
export const selectCount = (s) => s.items.reduce((n, i) => n + i.qty, 0);
export const selectBanner = (s) => s.banner;
Tests with render counts
The test counts how many times each component function runs. It checks the cart count through add (new line, existing line), remove (present and absent id) and clear (non-empty and already empty), proves the count component stays out of banner updates, and then renders the same count component against a whole-state context value as the baseline that must fail the "stays at 1" claim. One test subscribes a plain listener to the store and checks that no-op actions (unknown id, empty clear, unchanged banner, unknown action type) never call it, because render counts alone cannot show that: the selected number is the same either way. A last test uses a selector that builds a new object on every call.
// cartStore.test.jsx
import { describe, it, expect, vi, afterEach } from 'vitest';
import { createContext, useContext, useReducer, useRef } from 'react';
import { render, screen, act, cleanup } from '@testing-library/react';
afterEach(cleanup);
import {
CartProvider, createStore, cartReducer, initialCart,
useCartSelector, useCartDispatch, selectCount, selectBanner,
} from './cartStore.jsx';
const renders = { count: 0, banner: 0 };
function CartCount() {
renders.count += 1;
const n = useCartSelector(selectCount);
return <span data-testid="count">{n}</span>;
}
function Banner() {
renders.banner += 1;
const t = useCartSelector(selectBanner);
return <span data-testid="banner">{t}</span>;
}
function setup() {
renders.count = 0; renders.banner = 0;
const store = createStore(cartReducer, initialCart);
render(<CartProvider store={store}><CartCount /><Banner /></CartProvider>);
return store;
}
describe('store with selector subscriptions', () => {
it('count component ignores unrelated fields and tracks add/remove/clear', () => {
const store = setup();
expect([renders.count, renders.banner]).toEqual([1, 1]);
act(() => store.dispatch({ type: 'setBanner', text: 'Sale' }));
expect(screen.getByTestId('banner').textContent).toBe('Sale');
expect([renders.count, renders.banner]).toEqual([1, 2]);
act(() => store.dispatch({ type: 'add', id: 'p1', name: 'Pen' }));
act(() => store.dispatch({ type: 'add', id: 'p1', name: 'Pen' }));
act(() => store.dispatch({ type: 'add', id: 'p2', name: 'Ink' }));
expect(screen.getByTestId('count').textContent).toBe('3');
expect(renders.count).toBe(4);
act(() => store.dispatch({ type: 'remove', id: 'p1' }));
expect(screen.getByTestId('count').textContent).toBe('1');
act(() => store.dispatch({ type: 'remove', id: 'nope' })); // no-op
act(() => store.dispatch({ type: 'clear' }));
expect(screen.getByTestId('count').textContent).toBe('0');
const afterClear = renders.count;
act(() => store.dispatch({ type: 'clear' })); // already empty: no-op
expect(renders.count).toBe(afterClear);
console.log('selector store: CartCount renders =', renders.count, '| Banner renders =', renders.banner);
});
it('no-op actions notify nobody, and a real change notifies once', () => {
const store = createStore(cartReducer, initialCart);
const listener = vi.fn();
store.subscribe(listener);
store.dispatch({ type: 'remove', id: 'nope' });
store.dispatch({ type: 'clear' });
store.dispatch({ type: 'setBanner', text: '' });
store.dispatch({ type: 'unknown' });
expect(listener).not.toHaveBeenCalled();
store.dispatch({ type: 'add', id: 'p1', name: 'Pen' });
expect(listener).toHaveBeenCalledTimes(1);
});
it('a component can update through the dispatch hook', () => {
const store = createStore(cartReducer, initialCart);
function AddButton() {
const dispatch = useCartDispatch();
return <button onClick={() => dispatch({ type: 'add', id: 'p1', name: 'Pen' })}>add</button>;
}
render(<CartProvider store={store}><AddButton /><CartCount /></CartProvider>);
act(() => screen.getByText('add').click());
expect(screen.getByTestId('count').textContent).toBe('1');
});
it('pitfall: a selector that builds a new object on every call is reported by React', () => {
const store = createStore(cartReducer, initialCart);
const spy = vi.spyOn(console, 'error').mockImplementation(() => {});
function Bad() {
const v = useCartSelector((s) => ({ n: s.items.length }));
return <span>{v.n}</span>;
}
let thrown = null;
try { render(<CartProvider store={store}><Bad /></CartProvider>); } catch (e) { thrown = e; }
const msgs = spy.mock.calls.map((c) => String(c[0]) + ' ' + String(c[1] ?? '')).join('\n');
spy.mockRestore();
console.log('thrown:', thrown && thrown.message.slice(0, 60));
console.log('first matching console.error line:', msgs.split('\n').find((l) => /getSnapshot/.test(l)));
console.log('console.error mentions getSnapshot caching:', /getSnapshot should be cached/.test(msgs));
expect(thrown !== null || /getSnapshot should be cached/.test(msgs)).toBe(true);
});
});
describe('without selectors (whole state in one context value)', () => {
it('the count component re-renders when the banner changes', () => {
const Ctx = createContext(null);
const c = { count: 0 };
let dispatchOut;
function Count() { c.count += 1; const { state } = useContext(Ctx); return <span>{selectCount(state)}</span>; }
function Root() {
const [state, dispatch] = useReducer(cartReducer, initialCart);
dispatchOut = dispatch;
return <Ctx.Provider value={{ state, dispatch }}><Count /></Ctx.Provider>;
}
render(<Root />);
act(() => dispatchOut({ type: 'setBanner', text: 'Sale' }));
console.log('whole-state context: CartCount renders =', c.count);
expect(c.count).toBe(2); // fails the selector store's "stays at 1" claim
});
});
Run with the setup below, the whole runner output (the Start at and Duration timing lines are removed with grep -vE 'Start at|Duration|^$') is:
RUN v2.1.8 /w
stdout | cartStore.test.jsx > store with selector subscriptions > count component ignores unrelated fields and tracks add/remove/clear
selector store: CartCount renders = 6 | Banner renders = 2
stdout | cartStore.test.jsx > store with selector subscriptions > pitfall: a selector that builds a new object on every call is reported by React
thrown: Maximum update depth exceeded. This can happen when a compon
first matching console.error line: Warning: The result of getSnapshot should be cached to avoid an infinite loop%s
console.error mentions getSnapshot caching: true
stdout | cartStore.test.jsx > without selectors (whole state in one context value) > the count component re-renders when the banner changes
whole-state context: CartCount renders = 2
✓ cartStore.test.jsx > store with selector subscriptions > count component ignores unrelated fields and tracks add/remove/clear
✓ cartStore.test.jsx > store with selector subscriptions > no-op actions notify nobody, and a real change notifies once
✓ cartStore.test.jsx > store with selector subscriptions > a component can update through the dispatch hook
✓ cartStore.test.jsx > store with selector subscriptions > pitfall: a selector that builds a new object on every call is reported by React
✓ cartStore.test.jsx > without selectors (whole state in one context value) > the count component re-renders when the banner changes
Test Files 1 passed (1)
Tests 5 passed (5)
Each stdout | header names the test that printed the lines under it. In the pitfall test, thrown: is the first 60 characters of the error React threw out of render, and first matching console.error line: is the first line React logged that mentions getSnapshot; both come from the Bad component, whose selector returns a new { n: ... } object on every call.
Reading it: CartCount rendered once on mount, did not re-render for the banner change, then rendered five more times for the five actions that changed the number (add, add, add, remove, clear). That is 6 in total. The banner component rendered twice (mount plus one banner change). With the whole-state context value the same component rendered twice after a single banner change.
Trade-offs and pitfalls
- Selectors must return stable values. Returning
{ n: ... }or.filter(...)from a selector creates a new object on each call, so React sees a changing snapshot on every check. In the run above React logged the warning shown and threw "Maximum update depth exceeded". Select primitives, select an existing object that the reducer preserved, or compute derived arrays outside the selector. - Never mutate state in the reducer. Listeners are only notified when the reducer returns a new object, and
Object.isequality is what React uses to decide a re-render. - Server rendering needs a third argument. Server rendering means React turns the component tree into an HTML string on a server (for example with
renderToString) before the browser takes over. react.dev says that if you omitgetServerSnapshot, "rendering the component on the server will throw an error." With the store above,renderToStringon a tree containing auseCartSelectorcomponent throwsMissing getServerSnapshot, which is required for server-rendered content. Will revert to client rendering.in React 18.3.1. If this store is used in server-rendered pages, pass a third function that returns the snapshot the server should render, such as() => selector(initialCart). - Ready-made options. Redux Toolkit ("our official recommended approach for writing Redux logic", https://redux.js.org/introduction/getting-started) is the established library for this shape. Recommendation: hand-rolling is reasonable for a cart; adopt a library when you need middleware (code that sits between
dispatchand the reducer to log, delay or transform actions), devtools (a browser extension that records every action and state for debugging) or many slices. - Complexity.
dispatchruns the reducer once and then every listener's selector, so the cost per dispatch is the number of listeners multiplied by the cost of one selector (written O(listeners x selector cost); O(...) describes how work grows with size).selectCountis O(lines). With thousands of subscribers, give each its own narrow selector or key listeners by slice. - Edge cases covered by the tests: adding the same product twice increments quantity, removing an unknown id and clearing an empty cart do nothing, and unrelated field changes do not re-render the count.
Running the code
Files: cartStore.jsx, cartStore.test.jsx, vitest.config.js.
npm init -y && npm pkg set type=module
npm i react@18.3.1 react-dom@18.3.1
npm i -D vitest@2.1.8 jsdom@25.0.1 @testing-library/react@16.1.0 @testing-library/dom@10.4.0
# vitest.config.js: export default { esbuild: { jsx: 'automatic' }, test: { environment: 'jsdom' } }
npx vitest run --reporter=verbose 2>&1 | grep -vE 'Start at|Duration|^$'
Run in a node:22 container (Node 22.23.3) with exactly those versions.
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).
After a user edits their name, the header still shows the old one while the profile page shows the new one. What is likely wrong with the state design, and how do you restructure it so there is a single source of truth, including a derived value like a cart total?
Sample Answer
Direct answer
The user's name is almost certainly stored in two places, and only one of them is updated by the edit. Typical causes: the header copied the name into its own state or its own slice when it mounted, or the profile page keeps a separate "profile" object while the header reads a separate "session user" object. The fix is to store each fact once (the user entity, keyed by id), let the header and the profile both read that one record (an entity: one object describing a thing such as a user, stored under its id), and compute anything that can be calculated from stored data (a cart total, a full name) while rendering instead of storing it. react.dev states the principle: "When the same data is duplicated between multiple state variables, or within nested objects, it is difficult to keep them in sync." and "If you can calculate some information from the component's props or its existing state variables during rendering, you should not put that information into that component's state." (https://react.dev/learn/choosing-the-state-structure).
Finding the cause, in order
- Reproduce and note which side is right. Here the profile page is right (it shows the saved name) and the header is stale, so the write succeeded and the header is reading a different copy.
- Find every place the name is read. Search the code for the field (
user.name,displayName). In React DevTools' Components panel, select the header component and look at its hooks: auseStateinitialised from props or from the store is a copy. If the app uses Redux or similar, open its devtools and look at the state tree for two paths holding the same name (for examplesession.user.nameandprofile.name). - Check the write path. In the Network panel, see whether the save returned the updated user and which store action received it. If only the profile slice handles the
saveSucceededaction, the other copy never hears about it. - Check the read side for cached fetches. If the header and profile each fetch the user with different cache keys, one cache entry stays old until it refetches. Use one key per entity.
- Fix the structure, not just the symptom. Patching the header to refetch after the edit leaves two copies that can drift again.
Restructuring to one source of truth
- Keep entities normalized (each record stored once, in a table keyed by id):
users.byId = { u1: { id, name } }, and refer to them by id:session.userId = 'u1'. "Current user" is an id, not a second copy of the record. - Write through a single action (a plain object telling the store what happened, such as
{ type: 'renameUser', id: 'u1', name: 'Grace' }) that changes the one record; the store's reducer, a function(state, action) => nextState, applies it. - Read through selectors (small functions that pick or compute a value from the whole state):
selectCurrentName = s => s.users.byId[s.session.userId].name. Header and profile both call it, so they cannot disagree. The store is the one object that holds the state, and a slice is one part of it, such asusersorcart. - Derived values are computed, not stored. The cart total comes from the lines:
selectTotal = s => sum(price * qty). A storedcart.totalfield must be updated by every code path that changes a line; the first path that forgets leaves it wrong.
The code, run
The test builds a small store with three kinds of data (session id, user records, cart lines) and checks three things: the fixed design updates header, profile and total from single writes; a header that copies the name into useState keeps showing the old name; and a stored total that one reducer path forgot to recompute drifts from the derived total.
// singleSource.test.jsx
import { describe, it, expect, afterEach } from 'vitest';
import { createContext, useContext, useState, useSyncExternalStore } from 'react';
import { render, screen, act, cleanup } from '@testing-library/react';
function createStore(reducer, initialState) {
let state = initialState;
const listeners = new Set();
return {
getState: () => state,
dispatch(action) {
const next = reducer(state, action);
if (Object.is(next, state)) return;
state = next;
listeners.forEach((l) => l());
},
subscribe(l) { listeners.add(l); return () => listeners.delete(l); },
};
}
afterEach(cleanup);
// Normalized state: entities by id, plus ids that point at them. Nothing is stored twice.
const initial = {
session: { userId: 'u1' },
users: { byId: { u1: { id: 'u1', name: 'Ada' } } },
cart: { lines: [{ sku: 'pen', price: 3, qty: 2 }, { sku: 'ink', price: 5, qty: 1 }] },
};
function reducer(s, a) {
switch (a.type) {
case 'renameUser':
return { ...s, users: { ...s.users, byId: { ...s.users.byId, [a.id]: { ...s.users.byId[a.id], name: a.name } } } };
case 'setQty':
return { ...s, cart: { lines: s.cart.lines.map((l) => (l.sku === a.sku ? { ...l, qty: a.qty } : l)) } };
default:
return s;
}
}
const Ctx = createContext(null);
const useSel = (sel) => { const st = useContext(Ctx); return useSyncExternalStore(st.subscribe, () => sel(st.getState())); };
// Selectors: the only place a "current user name" or a "total" is computed.
const selectCurrentName = (s) => s.users.byId[s.session.userId].name;
const selectTotal = (s) => s.cart.lines.reduce((sum, l) => sum + l.price * l.qty, 0);
function HeaderFixed() { return <span data-testid="header">{useSel(selectCurrentName)}</span>; }
function ProfileFixed() { return <span data-testid="profile">{useSel(selectCurrentName)}</span>; }
function TotalFixed() { return <span data-testid="total">{useSel(selectTotal)}</span>; }
// Buggy design: the header copies the name into its own state when it mounts.
function HeaderCopy() {
const name0 = useSel(selectCurrentName);
const [name] = useState(name0);
return <span data-testid="header">{name}</span>;
}
describe('single source of truth', () => {
it('fixed design: header, profile and total all follow one write', () => {
const store = createStore(reducer, initial);
render(<Ctx.Provider value={store}><HeaderFixed /><ProfileFixed /><TotalFixed /></Ctx.Provider>);
expect(screen.getByTestId('total').textContent).toBe('11'); // 3*2 + 5*1
act(() => store.dispatch({ type: 'renameUser', id: 'u1', name: 'Grace' }));
act(() => store.dispatch({ type: 'setQty', sku: 'pen', qty: 4 }));
expect(screen.getByTestId('header').textContent).toBe('Grace');
expect(screen.getByTestId('profile').textContent).toBe('Grace');
expect(screen.getByTestId('total').textContent).toBe('17'); // 3*4 + 5*1
});
it('copy-into-local-state design: the header keeps the old name', () => {
const store = createStore(reducer, initial);
render(<Ctx.Provider value={store}><HeaderCopy /><ProfileFixed /></Ctx.Provider>);
act(() => store.dispatch({ type: 'renameUser', id: 'u1', name: 'Grace' }));
console.log('copy design -> header:', screen.getByTestId('header').textContent, '| profile:', screen.getByTestId('profile').textContent);
expect(screen.getByTestId('profile').textContent).toBe('Grace');
expect(screen.getByTestId('header').textContent).toBe('Ada'); // the reported bug
});
it('a stored total drifts when a write path forgets it; the derived total cannot', () => {
const stored = { ...initial, cart: { ...initial.cart, total: 11 } };
const reducerStoredTotal = (s, a) => {
if (a.type === 'setQty') { const n = reducer(s, a); return { ...n, cart: { ...n.cart, total: s.cart.total } }; } // forgot to recompute
return reducer(s, a);
};
const st = createStore(reducerStoredTotal, stored);
st.dispatch({ type: 'setQty', sku: 'pen', qty: 4 });
const storedTotal = st.getState().cart.total;
const derivedTotal = selectTotal(st.getState());
console.log('stored total:', storedTotal, '| derived total:', derivedTotal);
expect(storedTotal).toBe(11);
expect(derivedTotal).toBe(17);
});
});
Run with the setup below, the whole runner output (the Start at and Duration timing lines are removed with grep -vE 'Start at|Duration|^$') is:
RUN v2.1.8 /w
stdout | singleSource.test.jsx > single source of truth > copy-into-local-state design: the header keeps the old name
copy design -> header: Ada | profile: Grace
stdout | singleSource.test.jsx > single source of truth > a stored total drifts when a write path forgets it; the derived total cannot
stored total: 11 | derived total: 17
✓ singleSource.test.jsx > single source of truth > fixed design: header, profile and total all follow one write
✓ singleSource.test.jsx > single source of truth > copy-into-local-state design: the header keeps the old name
✓ singleSource.test.jsx > single source of truth > a stored total drifts when a write path forgets it; the derived total cannot
Test Files 1 passed (1)
Tests 3 passed (3)
Where the bugs are in the test code. In the second test, HeaderCopy is the broken design: const [name] = useState(name0) uses the store's name only as the initial value, so after renameUser the store says Grace, ProfileFixed re-renders with Grace, and the header still holds Ada (the first log line). In the third test, reducerStoredTotal is the deliberately forgetful reducer: its setQty branch calls the normal reducer, which changes the line, and then puts the old s.cart.total (11) back instead of recomputing it. After the pen quantity goes from 2 to 4, the stored field still reads 11 while selectTotal adds up the lines again and returns 3 x 4 + 5 x 1 = 17 (the second log line).
The cart is 2 pens at 3 and 1 ink at 5, so the total starts at 3 x 2 + 5 x 1 = 11. After the pen quantity becomes 4 the total is 3 x 4 + 5 x 1 = 17. The stored total stayed 11 because that reducer path did not recompute it; the derived total is 17 with no extra code.
Trade-offs and pitfalls
- Copying props into state (
useState(props.name)) only reads the prop once, on mount. If the value must follow the source, do not copy it. If you truly need an editable draft, name it as a draft (draftName) and initialise it deliberately. - Derived values can be expensive. For a total over a handful of lines, recomputing on render is free. For large lists, memoize the selector (cache its last result and reuse it while its inputs are the same), so it recomputes only when its inputs change.
- Normalization has a cost. Nested server responses must be flattened on the way in, and lists store ids and join to records on read. It pays off when the same entity appears in several places (header, profile, comments, mentions).
- A server-state cache is another store. If the user comes from a fetch library, let that cache hold the user and read it everywhere with one key; do not copy it into a second store.
- Optimistic edits: if the header should change before the server confirms, update the one record optimistically and roll back that record on failure; with one copy, there is one thing to roll back.
Running the code
Files: singleSource.test.jsx, vitest.config.js.
npm init -y && npm pkg set type=module
npm i react@18.3.1 react-dom@18.3.1
npm i -D vitest@2.1.8 jsdom@25.0.1 @testing-library/react@16.1.0 @testing-library/dom@10.4.0
# vitest.config.js: export default { esbuild: { jsx: 'automatic' }, test: { environment: 'jsdom' } }
npx vitest run --reporter=verbose 2>&1 | grep -vE 'Start at|Duration|^$'
Run in a node:22 container (Node 22.23.3) with exactly those versions.
Two setState calls in a click handler produce one render, but the same two calls inside a setTimeout used to produce two. Explain batching and what changed in React 18.
Sample Answer
Batching means React groups several state updates into one re-render instead of re-rendering after each setter call (a setter is the second value useState returns, such as setCount). Before React 18 this happened only for updates made inside React's own event handlers (an onClick prop, for example). Updates made from a setTimeout, a promise callback or a native DOM listener ran synchronously, so each setter call caused its own render. React 18 batches updates from every source, which is called automatic batching, but only for apps that mount with createRoot. An app still mounted with the legacy ReactDOM.render keeps the old behaviour. Mounting is the one line in the app's entry file that attaches React to a page element: createRoot(element).render(<App />) creates a modern root (the object React 18 uses to manage a mounted tree), while ReactDOM.render(<App />, element) creates a legacy root that works as React 17 did.
What the docs say changed
The React 18 release post says: "Batching is when React groups multiple state updates into a single re-render for better performance. Without automatic batching, we only batched updates inside React event handlers. Updates inside of promises, setTimeout, native event handlers, or any other event were not batched in React by default."
The useState reference describes the mechanism from the handler's point of view: "It updates the screen after all the event handlers have run and have called their set functions." The setter does not render; it queues an update, and React renders once afterwards with all queued updates applied.
What the setter does, step by step
setCount(c => c + 1)records the update in a queue attached to that state variable. The variable in your current closure (thecountyou read in this render's function) does not change.setFlag(f => !f)queues a second update on another variable.- When the current batch ends, React runs the component function once. It applies both queued updates in order, so the function sees the new
countand the newflagtogether. - React compares the new output to the old and updates the DOM.
The visible consequences are that the screen never shows a half-updated state (count changed but flag not yet), and that the component function runs once instead of twice.
Measured: the same two setters from several triggers on two root types
The component calls two setters (count and flag) per trigger and counts how many times its function runs. The demo mounts it once with createRoot and once with the legacy ReactDOM.render, fires each trigger, and asserts the counts. On the modern root it fires four triggers (a React onClick, a setTimeout, a promise callback and a native DOM listener) plus a flushSync case; on the legacy root it fires three (onClick, setTimeout, promise). flushSync is the React API that forces a synchronous render, and here it sits between the two setters.
The first lines of the listing are environment setup. JSDOM builds a fake browser page and the next three lines expose its window, document and navigator as globals. IS_REACT_ACT_ENVIRONMENT is set to true while React and Testing Library load, then to false before the measurements: with false, React treats updates as arriving from a real page, outside the act() test wrapper that would otherwise flush them, so the batching you see is the real batching. The legacy mount function swaps console.error for a collector because ReactDOM.render logs a deprecation warning through it in React 18, and the demo prints the start of that message. The hooks and Testing Library names that the listing destructures are not used below and can be ignored.
// batching.mjs
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;
Object.defineProperty(globalThis, 'navigator', { value: dom.window.navigator });
globalThis.IS_REACT_ACT_ENVIRONMENT = true;
const React = (await import('react')).default;
const { useState, useEffect, useMemo, useCallback, useRef, memo, useReducer } = React;
const { render, screen, fireEvent, cleanup, act, waitFor } = await import('@testing-library/react');
const h = React.createElement;
const ReactDOM = await import('react-dom');
const { createRoot } = await import('react-dom/client');
const { flushSync } = ReactDOM;
globalThis.IS_REACT_ACT_ENVIRONMENT = false; // updates happen outside act(), as in a real page
let renders = 0;
let api;
function Counter() {
const [count, setCount] = useState(0);
const [flag, setFlag] = useState(false);
renders++;
api = {
twice() { setCount((c) => c + 1); setFlag((f) => !f); },
twiceFlushed() { flushSync(() => setCount((c) => c + 1)); flushSync(() => setFlag((f) => !f)); },
staleTwice() { setCount(count + 1); setCount(count + 1); }, // both read this render's count
updaterTwice() { setCount((c) => c + 1); setCount((c) => c + 1); },
};
return h('button', { id: 'b', 'data-count': count, onClick: () => api.twice() }, count + ':' + flag);
}
const tick = () => new Promise((r) => setTimeout(r, 30));
const results = {};
async function measure(name, mount, trigger) {
renders = 0;
const host = document.createElement('div');
document.body.appendChild(host);
const unmount = mount(host);
await tick();
const before = renders;
await trigger(host.firstChild);
await tick();
results[name] = renders - before;
console.log(name.padEnd(36), '2 setState calls ->', results[name], 'render(s), label', host.firstChild.textContent);
unmount();
host.remove();
}
const modern = (host) => { const root = createRoot(host); root.render(h(Counter)); return () => root.unmount(); };
const legacyWarnings = [];
const legacy = (host) => {
const orig = console.error;
console.error = (...a) => legacyWarnings.push(String(a[0]).slice(0, 60));
ReactDOM.render(h(Counter), host);
console.error = orig;
return () => { const o = console.error; console.error = () => {}; ReactDOM.unmountComponentAtNode(host); console.error = o; };
};
const triggers = {
'React onClick': (btn) => btn.click(),
'setTimeout': () => new Promise((r) => setTimeout(() => { api.twice(); r(); }, 0)),
'promise .then': () => Promise.resolve().then(() => api.twice()),
'native listener': (btn) => {
btn.addEventListener('ping', () => api.twice()); // a listener added outside React
btn.dispatchEvent(new window.Event('ping'));
},
};
for (const [n, t] of Object.entries(triggers)) await measure('createRoot + ' + n, modern, t);
await measure('createRoot + flushSync between', modern, () => api.twiceFlushed());
await measure('legacy ReactDOM.render + onClick', legacy, triggers['React onClick']);
await measure('legacy ReactDOM.render + setTimeout', legacy, triggers['setTimeout']);
await measure('legacy ReactDOM.render + promise', legacy, triggers['promise .then']);
console.log('legacy warning starts:', legacyWarnings[0]);
assert.equal(results['createRoot + React onClick'], 1);
assert.equal(results['createRoot + setTimeout'], 1);
assert.equal(results['createRoot + promise .then'], 1);
assert.equal(results['createRoot + native listener'], 1);
assert.equal(results['createRoot + flushSync between'], 2);
assert.equal(results['legacy ReactDOM.render + onClick'], 1);
assert.equal(results['legacy ReactDOM.render + setTimeout'], 2);
assert.equal(results['legacy ReactDOM.render + promise'], 2);
// Reading state from the closure versus using an updater, with batching on.
const host = document.createElement('div'); document.body.appendChild(host);
const root = createRoot(host); root.render(h(Counter)); await tick();
api.staleTwice(); await tick();
const afterStale = host.firstChild.dataset.count;
api.updaterTwice(); await tick();
const afterUpdater = host.firstChild.dataset.count;
console.log('count after staleTwice:', afterStale, ' after updaterTwice:', afterUpdater);
assert.equal(afterStale, '1'); assert.equal(afterUpdater, '3');
root.unmount();
console.log('all assertions passed');
Run in a node:22 container (Node 22.23.3, React 18.3.1, jsdom), it prints:
createRoot + React onClick 2 setState calls -> 1 render(s), label 1:true
createRoot + setTimeout 2 setState calls -> 1 render(s), label 1:true
createRoot + promise .then 2 setState calls -> 1 render(s), label 1:true
createRoot + native listener 2 setState calls -> 1 render(s), label 1:true
createRoot + flushSync between 2 setState calls -> 2 render(s), label 1:true
legacy ReactDOM.render + onClick 2 setState calls -> 1 render(s), label 1:true
legacy ReactDOM.render + setTimeout 2 setState calls -> 2 render(s), label 1:true
legacy ReactDOM.render + promise 2 setState calls -> 2 render(s), label 1:true
legacy warning starts: Warning: ReactDOM.render is no longer supported in React 18.
count after staleTwice: 1 after updaterTwice: 3
all assertions passed
Reading it: with createRoot every trigger gives 1 render, except the flushSync case, which gives 2 because it asks React to render after the first setter before the second runs. With the legacy root, the onClick case is 1 but the setTimeout and promise cases are 2, which is the behaviour in the question. The same component, trigger and setters give 1 render under createRoot and 2 under the legacy root for the setTimeout and promise cases, so the root type is what changed the result.
The part that surprises people: batching does not update the variable you just set
The count after line of the output shows a second consequence of queuing. staleTwice calls setCount(count + 1) twice; both calls read the same count from the render's closure, so the result is 1 after both. updaterTwice passes functions, setCount(c => c + 1), and each function receives the value left by the previous queued update, so the result goes from 1 to 3. Use the updater form whenever the new value depends on the old one.
Trade-offs and pitfalls
- Upgrading the package is not enough. Switching
ReactDOM.rendertocreateRootis what enables the new behaviour, and the legacy call also prints a warning that it is no longer supported in React 18. - Code that relied on a synchronous render after a setter in a timer (reading the DOM right after
setState) can break after the switch. If you genuinely need the DOM updated first, wrap that one update influshSync, and expect it to cost an extra render. - Do not count on batching for correctness. Write components so that any sequence of renders is valid, because how many renders happen is React's decision, not part of your component's contract.
- Tests: assert with a render counter as in the demo, or with the React DevTools Profiler, not with timing.
Running the code
mkdir batching && cd batching && printf '{"type":"module"}' > package.json
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 batching.mjs # the listing above
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.