Skip to content

    Frontend System Design

    Component API and Data Model Design Rounds

    Work a component API and data model design round on a comment thread: store each fact once, derive the view, type out illegal states and say who owns what.

    By Published 12 min read

    Share

    Standard lessonintermediateReact labFrontend System Design

    Before this: The Front-End Architect Interview Framework, Component Composition and API Design

    What you'll learn: By the end of this lesson you will be able to run a component API and data model round in a fixed order: list the operations, choose entities and ids, split stored facts from derived ones, return named failures from operations, design props so illegal combinations do not type-check, state who owns each piece of state, and test the result by role and behaviour.

    Think of a library. The catalogue has one card per book, and every other list (by author, by shelf, "books on loan") is worked out from the cards. The circulation desk is what the public sees: a few clear actions with a few clear refusals ("that book is already on loan"). If the shelf lists are kept by hand alongside the cards, sooner or later they disagree. A design round asks you to build both parts, and to explain the line between them.

    The running example is a comment thread under a product question on the grocery marketplace's product page (the ShopStream front end). Shoppers ask, others reply, replies nest, a comment can be deleted, and a long branch can be collapsed. All names and text in the lab are invented. Prerequisites: the Component Composition and API Design lesson for the props toolkit and Derived and Normalized State for the data side; this lesson shows how an interviewer's prompt combines them. It follows the interview framework lesson of this module, which sets out how to run a round.

    The core idea

    1. Data model first, then the API. The component's props are a function of the model: what is stored, what is derived and which operations exist decide what the component can ask for.
    2. Store each fact once and derive the rest. react.dev lists five principles for state structure, among them avoiding redundant state and avoiding duplication; a second copy of a fact is a place to be wrong.
    3. Say who owns each piece of state. React's docs call this a single source of truth: for each unique piece of state you choose the component that owns it.

    The round in six steps

    Figure 1. The six steps

    flowchart LR accTitle: The six steps of a component API and data model round accDescr: Six steps in order. Operations and states, entities and ids, stored versus derived, operations that return named results, props and ownership, tests and failure cases. A dotted arrow goes back from tests to operations when a test exposes a missing rule. A["1. Operations
    and states"] --> B["2. Entities
    and ids"] B --> C["3. Stored
    versus derived"] C --> D["4. Operations
    return named results"] D --> E["5. Props
    and ownership"] E --> F["6. Tests and
    failure cases"] F -.->|"missing rule"| A

    How to read this: steps 1 to 4 are the data model and need no React; steps 5 and 6 are the component. Saying the step you are on keeps an interviewer able to follow, and the dotted arrow is honest: a test often shows an operation you forgot.

    For the thread, step 1 reads: add a top-level comment, add a reply, delete a comment, collapse or expand a branch, show a flat list with indentation. States: an empty thread, a thread with comments, a deleted comment that still has replies.

    Entities, ids and what is stored

    Illustration 1: the minimal example

    A server often answers with replies nested inside their parent. react.dev's advice for deeply nested state is to make it flat: instead of each item holding an array of its children, each item holds an id and a table maps ids to items. Redux's guide gives the rules: each type of data gets its own table keyed by id, references are by id, and arrays of ids give ordering. The lab applies them to the thread. The first block is the whole stored shape:

    export interface CommentRecord {
      readonly id: CommentId;
      readonly parentId: CommentId | null;
      readonly author: string;
      readonly body: string;
      readonly deleted: boolean;
    }
    
    export interface ThreadState {
      readonly byId: Readonly<Record<CommentId, CommentRecord>>;
      readonly order: readonly CommentId[]; // insertion order, which is also the display order among siblings
    }

    One departure from the docs' examples is deliberate and worth saying aloud. The examples store a childIds array on each parent. Here each comment stores its parentId, and the list of children is derived by childIndex from order. That is one fact per relationship instead of two, so a bad update cannot make the parent's list and the child's pointer disagree. The cost is that the index is rebuilt each time it is needed; the lab does not measure whether that matters for a large thread, and child-id arrays make reordering siblings easier. Both are defensible if you name the trade-off.

    Ids also serve rendering: react.dev says keys should come from your data, such as database ids, must not change, and should not be generated while rendering. The component uses the comment id as the row key, never the array index.

    Expected output, captured from a real run (sections 1 to 3 of the demo, Node 26.13.1):

    === 1. a nested payload, stored flat
    records: 6, order: c1 c2 c3 c4 c5 c6
    c4 is stored as {"id":"c4","parentId":"c3","author":"Ben","body":"The lid only.","deleted":false}
    
    === 2. the visible rows, derived from the state and the collapsed set
    c1 Asha: Does the lid come off for cleaning?
      c2 Ben: Yes, it twists off.
        c3 Asha: Is it dishwasher safe?
          c4 Ben: The lid only.
      c5 Chen: Mine arrived without a lid.
    c6 Dana: How long is delivery to the north region?
    
    === 3. collapse c2 (state unchanged, only the collapsed set differs)
    c1 Asha: Does the lid come off for cleaning?
      c2 Ben: Yes, it twists off.  (+2 hidden)
      c5 Chen: Mine arrived without a lid.
    c6 Dana: How long is delivery to the north region?
    rows shown: 6 -> 4; records stored: 6

    Section 1 shows the nested payload stored as six flat records; section 2 is the visible list derived from state plus the collapsed set; section 3 collapses c2 and the list shrinks from 6 rows to 4 while the stored records stay at 6. Collapsing is not stored in the thread because it is a viewing choice, which is why it lives next to the component, not in the model.

    Operations that return named results

    An operation that can be refused should say why, in a type a caller can switch on. addReply returns either the new state or a Failure: empty-body, duplicate-id, unknown-parent or max-depth. The component then needs no rules of its own: its reply form shows whatever the container hands back, and keeps the draft when a reply is refused.

    Figure 2. A refused reply

    sequenceDiagram accTitle: A reply that the model refuses accDescr: The shopper submits a blank reply. The form calls onReply on the container, which asks the model to add the reply. The model refuses with empty-body, the container returns that reason, and the form shows an alert and keeps the draft. A later valid reply is accepted, the container stores the new state and the form closes. participant U as Shopper participant F as Reply form participant C as Container participant M as Pure model U->>F: submits a blank reply F->>C: onReply(parentId, text) C->>M: addReply(state, parentId, input) M-->>C: refused, empty-body C-->>F: returns empty-body Note over F: alert shown, draft kept U->>F: submits real text F->>C: onReply(parentId, text) C->>M: addReply(...) M-->>C: ok, new state C-->>F: returns null Note over F: form closes

    How to read this: the rules live in the model, the container only forwards, and the form only displays the answer. No component re-implements "is a blank reply allowed".

    Deleting deserves its own decision. Removing a comment that has replies would orphan them, so the model keeps a tombstone (deleted: true, empty body) and the derived list drops a tombstone only when nothing live is below it.

    Illustration 3: a failure and its edges

    Expected output, captured from a real run (sections 4 to 6 of the demo):

    === 4. delete c2 (it has live replies) then c5 (a leaf)
    c1 Asha: Does the lid come off for cleaning?
      c2 [deleted]
        c3 Asha: Is it dishwasher safe?
          c4 Ben: The lid only.
      c5 Chen: Mine arrived without a lid.
    c6 Dana: How long is delivery to the north region?
    -- then c5:
    c1 Asha: Does the lid come off for cleaning?
      c2 [deleted]
        c3 Asha: Is it dishwasher safe?
          c4 Ben: The lid only.
    c6 Dana: How long is delivery to the north region?
    
    === 5. a tombstone with nothing live below it is dropped
    c6 Dana: How long is delivery to the north region?
    
    === 6. what the model refuses
    empty body         : refused (empty-body)
    unknown parent     : refused (unknown-parent)
    duplicate id       : refused (duplicate-id)
    reply to depth 3   : refused (max-depth)
    delete unknown     : refused (unknown-comment)
    reply to depth 2   : accepted, 7 comments

    Read it top to bottom. Deleting c2 keeps its row as [deleted] because c3 and c4 live under it. Deleting the leaf c5 removes its row. Section 5 deletes everything under c1 and then c1 itself: the whole branch disappears, leaving one row. Section 6 lists the refusals, including a reply to depth 3, which is the limit set by MAX_DEPTH, and an accepted reply to depth 2 whose text was trimmed.

    Types that forbid illegal states

    TypeScript's handbook says that when every member of a union has a common property with literal types, the union is a discriminated union and checking that property narrows to one member. The lab uses that twice.

    First, the row the view receives. A tombstone has no author and no body field, so a component cannot print an author for a deleted comment, because the type does not carry one:

    export type ThreadRow =
      | (RowBase & { readonly kind: "comment"; readonly author: string; readonly body: string })
      | (RowBase & { readonly kind: "tombstone" });

    Second, the props. Collapsed state is either controlled by the parent or kept by the component. react.dev calls a component controlled when its important information is driven by props and uncontrolled when it holds local state, says controlled components are maximally flexible but require the parent to configure them fully, and notes the two terms are not strict. A union makes the pairing explicit:

    export type CollapseProps =
      | {
          readonly collapsed: ReadonlySet<CommentId>;
          readonly onCollapsedChange: (next: ReadonlySet<CommentId>) => void;
          readonly defaultCollapsed?: never;
        }
      | {
          readonly collapsed?: undefined;
          readonly defaultCollapsed?: ReadonlySet<CommentId>;
          readonly onCollapsedChange?: (next: ReadonlySet<CommentId>) => void;
        };

    Controlled mode without a handler, and controlled plus a default, are both type errors; the lab's test file has two @ts-expect-error lines, and tsc fails if either stops being an error.

    Figure 3. Who owns what

    Ownership in the comment threadServer answer to Container (normalise); Container to Pure model (add, delete); Container to CommentThread (thread, onReply); Parent to CommentThread (collapsed (optional))Server answer: nested repliesServer answernested repliesContainer: owns thread dataContainerowns thread dataCommentThread: owns form, draftCommentThreadowns form, draftPure model: rules, derived rowsPure modelrules, derivedrowsParent: may own collapsedParentmay own collapsednormaliseadd, deletethread, onReplycollapsed (optional)

    How to read this: the thread data has one owner, the container, which asks the model to apply rules. The component owns only what is UI: the open reply form and its draft. The collapsed set belongs to the component unless a parent chooses to control it.

    The component API

    Illustration 2: the realistic example

    On the product page the thread is one component with five props. Each row says what the prop is and why it exists.

    Prop Kind Why it exists
    thread Data The single source of truth, owned by the caller
    onReply(parentId, body) Event, returns Failure or null The caller decides if it is allowed; the form shows the answer
    collapsed / defaultCollapsed / onCollapsedChange Controlled or uncontrolled One piece of state, two ownership modes, never both
    renderBody(row) Slot The caller draws a comment body; tombstones never reach it
    empty Slot What to show when there is nothing

    The slot follows the "holes, not flags" idea of the composition lesson: no showAvatar, markdown or highlightAuthor props. A caller who wants Markdown passes renderBody.

    Accessibility is a sketch, not a finished widget. Each collapse button carries aria-expanded, which MDN describes as indicating whether a control is expanded or collapsed and whether the controlled elements are displayed or hidden; MDN also says a toggling button should set aria-controls to the toggled widget's id, which the lab does not do. The reply form's label wraps the textarea, and MDN says that nesting makes the association implicit and that not all assistive technologies support it. A refused reply is a role="alert"; MDN says alert is equivalent to aria-live="assertive" and aria-atomic="true", and must be used sparingly. A reply refusal the user caused and must fix is a reasonable use.

    Trade-offs

    Choice Gain Cost
    parentId plus derived children One fact per relationship Index rebuilt per call (not measured)
    childIds on each parent (the docs' shape) Cheap child lookup and reordering Two facts that can disagree
    Tombstone on delete Replies keep their place The record keeps data the view hides
    Union props (controlled or not) Illegal mixes fail at compile time More type code; callers must read the union
    Slots over flag props The API stays small Callers write more JSX
    Return Failure or null from onReply The form can explain a refusal A synchronous callback; async needs a different shape

    Build it

    The lab is examples/frontend/labs/comment-thread-design-round: a pure core (src/model.ts), a thin React component and container (src/CommentThread.tsx) and 30 tests, 18 on the model and 12 on the component with Testing Library under jsdom. Testing Library's documentation ranks getByRole as the top preference for almost everything, so the tests find buttons by role and accessible name ("Hide replies to Ben") and the form by its label.

    cd examples/frontend/labs/comment-thread-design-round
    ../../node_modules/.bin/vitest run        # 30 passed
    ../../node_modules/.bin/tsc -p tsconfig.json
    node src/demo.ts                          # the trace above

    Verified. In the run made for this lesson (Node 26.13.1, Vitest 5.1.0, React 19.3.1, TypeScript 7.0.2) 30 tests passed and the typecheck was clean. As a "break it" check, deleting the tombstone-dropping line in visibleRows made exactly one test fail ("drops a tombstone that has nothing live below it"), and the line was restored and the suite re-run green. jsdom is not a browser: layout, focus rings and screen-reader output were not observed, and a passing test shows only what jsdom did.

    In practice: a product questions thread

    NOTE

    This is a realistic scenario, not a case history. It is a composite built from common production patterns. It describes no specific company or product, and every number in it is an illustrative assumption.

    The situation

    The product page gains a questions section. The first version keeps the server's nested JSON in state and a recursive component renders it. Product now wants "collapse this branch", "delete my comment" and a depth limit. Every change touches a recursive update function that copies each level.

    Starting architecture

    Figure 4. Today: nested state, recursive component

    Starting architecture: nested state and a recursive rendererQuestions API to Page state; Page state to Recursive view (props)Questions API: nested repliesQuestions APInested repliesPage state: the nested treePage statethe nested treeRecursive view: rules insideRecursive viewrules insideprops

    How to read this: the warning boxes hold the rules (depth, deletion, collapsing) mixed with drawing, so each new rule edits both the update path and the component.

    Options considered

    Option What it fixes What it costs Risk
    Keep nested state, add a helper per rule Small diff A recursive copy per operation Rules spread across the view
    Flat records plus a pure model, derived rows One place for rules; testable without React A normalising step and a derived list Index and rows are recomputed
    Let a library own it Less code A new dependency and its model The domain rules still need a home

    The decision

    Field Decision record
    Context New rules (collapse, delete, depth) are expensive to add to nested state and are untested.
    Decision Normalise to flat records with parentId, put every rule in a pure model returning named results, derive a flat list of rows, and give the component union props with a controlled or uncontrolled collapsed set.
    Consequences, good Rules are tested without React; the view cannot show a deleted author; the form explains refusals.
    Consequences, bad A normalising step, more types, and a derived list to keep an eye on for large threads.
    Revisit when Threads grow large enough that rebuilding the index shows up in a profile, or replies must load in pages.

    Rollout and verification

    1. Write the operations and refusals as a table before any code, and agree the depth limit.
    2. Land the model with its tests behind the existing component; the old view is unchanged.
    3. Switch the view to derived rows and compare the rendered text on sample threads.
    4. Check by keyboard and with a screen reader that the toggle, the form and the refusal are usable; the lab's tests cannot show that.

    The 2 a.m. failure

    A support ticket: a deleted comment's author name still appears in the page's accessible text. The row type does not carry it, but a developer added a renderBody that read the author straight from the record.

    First three checks: (1) find which slot reads the raw record; (2) check whether the tombstone case is covered for that slot; (3) look at what the server still sends. Mitigation: pass the slot the row only. Follow-up: a test that renders a tombstone through every slot.

    Architect's notes

    • Run the steps in order and say them aloud. The sequence is the answer.
    • Make the refusal part of the type. A Failure union is documentation a compiler checks.
    • Keep view choices out of the model. Collapsed, selected and focused belong next to the component.
    • Name the departure. If you diverge from a documented shape, say why and what it costs.

    Common mistakes

    • Storing the children list and the parent pointer. Two facts will disagree.
    • Storing the selected object instead of its id. react.dev's fix is to keep the id and derive the object.
    • Flag props for every variation instead of a slot.
    • Letting both value and defaultValue through and picking a winner at run time.
    • Using the array index as a key in a list that can change.
    • Claiming accessibility from a jsdom test.

    Key takeaways

    • Model first: operations, entities and ids, then stored versus derived, then the props.
    • Store each fact once; derive the list the view needs.
    • Return named failures; let the component show them.
    • Put illegal combinations out of reach of the type checker.
    • Name the owner of every piece of state, and whether the parent may take it over.

    Practice exercises

    Exercise 1: Starter (30 min). Add a "pinned" comment to the model: decide whether it is stored or derived, then write the test.

    Exercise 2: Intermediate (2 hours). Change the model to store childIds on each record. Write the test that makes the two facts disagree, and list what you would now have to keep in sync.

    Exercise 3: Advanced (half day). Replace the synchronous onReply with an async one that can fail on the network. Decide what the form shows while waiting and while failed, and say which lesson's states apply (Error, Loading and Empty States).

    In this course:

    Official documentation

    Ask about this article

    Get answers grounded in this post. AI-generated — based on this article, and may be imperfect.

    Scaled AI Weekly

    Enjoyed this? Get more like it every Monday.

    Real architecture decisions, LLMOps patterns that survive production, and engineering leadership advice — from 12+ years of building at enterprise scale. Free. No spam. Unsubscribe anytime.

    Get new articles by email

    Free. We email a confirmation link first, and you can unsubscribe from any email.

    Join engineers building production AI systems

    Comments