FSD Frontend System Design

Part V — The Craft · Lesson 10.9

Nested Comments

In one lineA recursive tree render over a flat, normalized store — with a depth cap so it stays usable.

Where you've seen itA Reddit thread where the fourteenth reply is two words wide.

  • Time17 min
  • DiagramFlat data → tree structure → recursive render
  • Chapter10 · Low Level Design

Diagram

diagram
diagram
diagram
DEPTH CAP — why it isn't optional

  depth 0  ████████████████████████████████████ 100%
  depth 3  ██████████████████████████ 76%
  depth 6  ████████████████ 52%
  depth 9  ███████ 28%
  depth 12 ██ 8%   ← unreadable on mobile

  After ~5 levels: stop indenting, or link to a focused sub-thread view.

How it works

  1. Store flat, keyed by id, with a parentId on each node — updates and inserts stay O(1).
  2. Build the children map once (parentId → [childIds]) and memoise it; rebuilding per render is the usual performance bug.
  3. Render recursively with a depth prop, capping indentation and offering "continue thread" beyond the cap.
  4. Collapse subtrees by storing a set of collapsed ids — collapsing must hide the whole subtree, not just direct children.
  5. Lazy-load deep replies. Fetch top-level comments with a couple of levels, then load more on demand.
jsx
const childrenOf = useMemo(() => {
  const map = new Map();
  for (const c of Object.values(byId))
    map.set(c.parentId, [...(map.get(c.parentId) ?? []), c.id]);
  return map;
}, [byId]);

function Comment({ id, depth = 0 }) {
  const kids = childrenOf.get(id) ?? [];
  if (depth > MAX_DEPTH) return <a href={`/thread/${id}`}>Continue thread →</a>;
  return (
    <li style={{ '--depth': depth }}>
      <Body id={id} />
      {kids.length > 0 && (
        <ul>{kids.map((k) => <Comment key={k} id={k} depth={depth + 1} />)}</ul>
      )}
    </li>
  );
}

Trade-offs

Recursive renderFlattened render
Mirrors the data, simple to readEasier to virtualize
Deep trees risk stack/perf issuesManual indent bookkeeping
Natural collapse semanticsBetter for thousands of nodes

Accessibility: nested <ul>/<li> gives screen readers real depth information for free. Collapse toggles follow the accordion contract from 10.8, and each comment should be reachable by keyboard without tabbing through every action button — consider a roving tabindex (8.2).

Interview angle

"Build Reddit-style nested comments."

  • Normalized flat store, memoised parent→children map, recursive component with a depth prop.
  • Cap indentation around five levels and link deeper threads to their own view — this is a UX requirement, not a shortcut.
  • For very large threads, flatten to a visible-nodes array and virtualize; recursion and virtualization don't compose easily.

Recap

  • Flat, normalized storage; tree derived and memoised at render.
  • Recursion needs a base case and a depth cap.
  • Collapse hides the subtree; nested lists give a11y depth for free.