State, snapshots, and derived data
Build a cart model that remains consistent under queued updates, changing stock and repeated user interaction.
What you will be able to do
- Identify the smallest authoritative state for a feature.
- Calculate derived views instead of synchronizing duplicate values.
- Explain stale closures and functional updates with a concrete cart example.
Before this lesson
Store decisions, derive consequences
For a cart, the essential client decision is which product IDs are selected and in what quantities. A line total, item count and empty-state message are consequences of those decisions and the catalogue snapshot. Storing every consequence independently creates more combinations than the product supports. You can accidentally show two items in the list and three in the badge. Derivation removes the need for a separate synchronization procedure.
Begin by naming the invariant: displayed totals must come from the same line snapshot displayed in the list. Write a pure function that normalizes quantities and computes totals. Use integer minor units in this exercise so multiplication is predictable. Production pricing still belongs to the server: a browser subtotal is a display estimate, never authorization to charge a user-supplied amount. This separates a UI consistency guarantee from a financial transaction guarantee.
Understand the value captured by an event
A render observes one state snapshot. An event handler created by that render closes over that snapshot. Calling the setter asks React to schedule another render; it does not rewrite the local variable already captured by the running handler. If quantity is two, three calls that each calculate quantity plus one all request the value three. They do not automatically represent three independent increments.
An updater function expresses a transition from the pending state: setQuantity(previous => previous + 1). Chaining transitions now has a clear interpretation even when React processes several updates together. Use this form when the next value depends on the previous value. For a replacement such as selecting a different product ID, the replacement value is often exactly the intended operation. The issue is semantic intent, not memorizing a rule that every setter needs a callback.
Client module
'use client';
import { useState } from 'react';
export default function Quantity({ stock }: { stock: number }) {
const [quantity, setQuantity] = useState(0);
const totalLabel = quantity === 1 ? '1 item' : `${quantity} items`;
return <div>
<p aria-live="polite">{totalLabel}</p>
<button disabled={quantity >= stock}
onClick={() => setQuantity(previous => Math.min(stock, previous + 1))}>
Add one
</button>
</div>;
}Keep identity separate from copied objects
Store a selected product ID rather than a second full copy of its product object. When catalogue data changes, look up the selected product in the current data. Otherwise the list can show a new title while the detail panel still displays the old copied title. The same reasoning applies to selected rows, active tabs and currently edited records. A draft is different: it is an intentionally independent working copy with an explicit save or discard lifecycle.
When updating arrays or objects in state, return a new structure for the part that changes. Mutating an old render snapshot changes what earlier closures can observe and makes comparison unreliable. Immutability is therefore a reasoning tool before it is a performance technique. Keep the model shallow when practical, and test that transitions do not alter their inputs. Deep cloning everything is rarely the best model for a small cart.
Use tests to expose contradictory states
Test empty carts, zero stock, negative input and quantities above stock. Ask what the interface should do when inventory falls after a user selected five units. The kata chooses to cap the displayed effective quantity to the current stock. A real checkout might instead retain the requested quantity and display a conflict. Neither policy should emerge accidentally from a button implementation; specify it before choosing state fields.
Do not add an Effect that calculates subtotal and then stores it in a second state variable. That introduces another update and a period where the old total can coexist with new lines. Calculate it while rendering. If the calculation later becomes measurably expensive, memoization can avoid repeated work, but it must not be required for correctness. An interview answer should first prove a consistent model and then justify any optimization with workload evidence.
Misconceptions to replace
Compare the tempting shortcut with the model you can verify in code.
- CLAIM TO CHALLENGECopying selectedProduct is always equivalent to storing selectedId.
- A more accurate model
A copied record can become stale when the current catalogue changes. An intentionally independent draft needs explicit save, cancel and conflict behavior.
- How to check it
R02 explains avoiding duplicated state; the state lesson contrasts references to current data with editable drafts.
- CLAIM TO CHALLENGEuseMemo is necessary to keep derived totals correct.
- A more accurate model
Derivation should be correct without memoization. Memoization can avoid repeated expensive work but cannot repair inconsistent state ownership.
- How to check it
R06 distinguishes render-time derivation from unnecessary synchronization Effects.
Mistakes to catch in your own code
- Do not treat state setters as assignments to the current render variable.
- Do not duplicate totals, selected objects and counts without a separate lifecycle reason.
- Do not trust browser-provided prices when executing an order.
Write it by hand
JavaScript logic playground
Derive a consistent cart summary
Implement solve(input). This sandbox runs the lesson's logic with FrontendX's isolated code runner. Next.js server behavior is verified in the project lab below.
- Implement solve({items}). Each item has id, quantity, stock and unitCents. Values are finite numbers; stock and unitCents are nonnegative integers.
- Normalize quantity by flooring it and clamping to the inclusive range zero through stock. Exclude zero-quantity lines. Return lines containing id and quantity, itemCount, subtotalCents and hasItems.
- Preserve input order and do not mutate input. This kernel checks display logic, not checkout security.
Tab moves to the next control. Use spaces to indent and return your answer from solve. Console output is not retained.
Inspect 4 test cases
- Empty cart
Input
{ "items": [] }Expected
{ "lines": [], "itemCount": 0, "subtotalCents": 0, "hasItems": false } - Two lines
Input
{ "items": [ { "id": "book", "quantity": 2, "stock": 4, "unitCents": 1250 }, { "id": "pen", "quantity": 3, "stock": 8, "unitCents": 150 } ] }Expected
{ "lines": [ { "id": "book", "quantity": 2 }, { "id": "pen", "quantity": 3 } ], "itemCount": 5, "subtotalCents": 2950, "hasItems": true } - Clamp and remove unavailable items
Input
{ "items": [ { "id": "a", "quantity": 9, "stock": 2, "unitCents": 100 }, { "id": "b", "quantity": 2, "stock": 0, "unitCents": 900 }, { "id": "c", "quantity": -3, "stock": 4, "unitCents": 700 } ] }Expected
{ "lines": [ { "id": "a", "quantity": 2 } ], "itemCount": 2, "subtotalCents": 200, "hasItems": true } - Fractional input becomes whole units
Input
{ "items": [ { "id": "a", "quantity": 2.9, "stock": 4, "unitCents": 199 } ] }Expected
{ "lines": [ { "id": "a", "quantity": 2 } ], "itemCount": 2, "subtotalCents": 398, "hasItems": true }
Reveal the worked solution and reasoning
function solve(input) {
const lines = [];
let itemCount = 0;
let subtotalCents = 0;
for (const item of input.items) {
const quantity = Math.min(item.stock, Math.max(0, Math.floor(item.quantity)));
if (quantity === 0) continue;
lines.push({ id: item.id, quantity });
itemCount += quantity;
subtotalCents += quantity * item.unitCents;
}
return { lines, itemCount, subtotalCents, hasItems: lines.length > 0 };
}A single normalized quantity drives the line, badge and total, so they cannot drift independently.
The algorithm is linear in the number of lines. The server must still determine the real transaction price.
Verify it in a real Next.js application
Next.js application lab
Prove cart consistency in the browser
Open the local application route /cart after starting the workbench. Follow the experiment and collect the evidence described below.
Make the change
- Inspect components/cart-provider.tsx, lib/domain.ts and app/cart/page.tsx. The shipped application already uses a reducer and derives the total from cart lines; its quantity limit is 99, not an inventory stock count.
- Add a product twice, open /cart, change its quantity, then enter zero. Explain the new line model and total after each transition. Test a negative, fractional and over-limit quantity against the reducer tests.
- Reload with a saved cart and observe the restoration state before storage is applied. In a disposable practice session, replace the saved cart with invalid JSON or invalid rows and check the documented empty or filtered recovery.
- As an explicit extension, add a derived item-count badge using the same lines. If you also add stock limits, introduce an authoritative stock input and tests; the shipped product model has no stock field.
Check the behavior
- The total equals the sum of the displayed quantities multiplied by their stored teaching prices.
- A zero quantity removes its line; invalid reducer quantities do not alter valid state.
- Storage restoration does not introduce a server/client initial-render mismatch.
- If the badge extension is implemented, it updates from the same line snapshot without a separately stored count.
Review the application reasoning
The runtime already persists the practice cart after hydration. That is browser-local persistence, not a server order or cross-device synchronization.
Browser prices are display data in this lab. A real checkout must re-read products, permissions and prices on the server before committing an order.
Open the project files and run instructions
A complete App Router application with catalogue routing, cart state, a task dashboard, practice sessions, tenant checks, cached data, hydration repairs, and HTTP streaming. Next.js 16.4.6 and React 19.3.0 are pinned in the project.
The playground opens a new editable copy. A local Node.js 22.14+ installation also runs the project. Use the local production build when measuring caching, streaming, or deployment behavior.
cd nextjs-interview-lab
npm ci
npm run dev
# In a second terminal
npm test
# Stop dev, then verify the production application
npm run build
npm start
# In a second terminal, install the test browser once
npx playwright install chromium
npm run test:e2eOpen http://localhost:3003. The project includes a credential-free practice account selector and a single-process file store. Those choices make experiments reproducible; the security and deployment lessons show what a production system needs.
Explain it in an interview
Give your answer aloud before opening the explanation. Then answer the follow-ups using your implementation as evidence.
01Why might three quantity updates add only one?
If all three calls compute quantity + 1 from the same render snapshot, they all enqueue the same replacement value. Functional updaters describe successive transitions instead. I would demonstrate both cases, then choose the form matching the event: replacement for an absolute selection, updater for a relative increment.
Follow-up questions
- What if the queue contains both replacement and updater operations?
- What changes when the handler awaits a request?
- React: state as a snapshotOfficial documentation
- React: queueing state updatesOfficial documentation
02Should subtotal be stored in state?
Usually not when it is fully determined by the current lines and prices. Deriving it makes the list and total share a source of truth. If the subtotal is an authoritative quote from a remote pricing service, that is separate server state with a version and expiry, and I would name it quote rather than pretending it is the same local calculation.
Follow-up questions
- When would useMemo help?
- How would you represent an expired server quote?
- React: choosing the state structureOfficial documentation
- React: you might not need an effectOfficial documentation
03Why store selectedId instead of selectedProduct?
An ID points to the current product record without duplicating it. A copied object can become stale after list refreshes. An editable draft may intentionally copy fields, but then save, cancel and conflict behavior must be explicit. The right model depends on whether the value is a reference to current data or an independent draft.
Follow-up questions
- What if the selected product disappears?
- How do you preserve unsaved edits during a refresh?
- React: choosing the state structureOfficial documentation
04What invariant would you test for a cart?
In this exercise, effective quantities are nonnegative integers bounded by stock, and the badge and subtotal are derived from those same quantities. I would test empty data and stock changes, not just clicking Add once. In a real order service I would additionally revalidate stock and price atomically at the mutation boundary.
Follow-up questions
- Why is disabling a button insufficient?
- What policy should apply when stock falls?
- Master Ventures interactive ballot assignmentEmployer assignment
- React: choosing the state structureOfficial documentation
- Data securityOfficial documentation
Check your understanding
Answer these without reopening the worked examples. The feedback explains the reasoning and the misconception behind each choice.
Your checkpoint
Loading your local progress.
Sources and further reading
- React: state as a snapshotOfficial documentation
- React: choosing the state structureOfficial documentation
- React: you might not need an effectOfficial documentation
- React: queueing state updatesOfficial documentation
- Master Ventures interactive ballot assignmentEmployer assignment
- ModernVivo Paper Explorer take-homeEmployer assignment
- Data securityOfficial documentation