Vibe coding with Claude Code course · Module 5: Reddit clone

Threads in a tree: comments that do not vanish quietly

10 min read ·
In this lesson10

A discussion has flared up under the post about the course to Tortuga. Morgan wants to sail north, Redbeard asks about drinking water, Polly warns about sharks, and Jack prefers Tortuga. In a flat list of ten entries nobody knows who is answering whom. Reddit arranges replies in indented threads, and that is what you build in this lesson, while the function that arranges the threads is again written by Claude Code only after the tests.

The problem: a flat list, a tree on screen

Comments will one day arrive from a database as a flat list. Each has a parentId, that is the id of the comment it answers, or null when it answers the post directly. The screen needs something different: a comment, under it its replies, under them further ones. Turning the list into such a tree is a few lines that an agent writes in a minute, and two places where a comment can vanish without any error. First: a reply stands on the list before its parent, for example when the database returns entries in another order. Second: the parent is gone, because someone deleted it.

A tree and recursion in one paragraph

A tree is a structure in which every node has a list of children of the same kind, like a casket with caskets inside. For us a node is a comment with a replies array, and in it again comments with their own replies. Recursion is a function or component that calls itself for its children. Every recursion needs an end condition, otherwise it would call itself forever. Here it is an empty replies array.

Request for Claude Code

The request names the edge cases outright, because any version passes the happy path:

Request for Claude Code:

Add comments to Crew Council. A comment has id, postId, parentId
(the parent's id or null), author, text and createdAt. In lib/comments.ts
write buildCommentTree(comments), which turns a flat list into a tree
(every node has replies), and countTotalComments(tree). Tests first
in lib/comments.test.ts: three levels of replies, a reply stored on
the list before its parent, a comment without an existing parent (it
stays at the top), the flat list unchanged after the call, a counter
across all levels. Run the tests before the code and after it. Do not
change the tests to make them pass. Do not finish until
npm run test -- --run is green, and show the result.

"Do not finish until..." is a completion condition written into the request, the simplest step of rigour from the Claude Code best practices. Claude knows what the end of the work looks like and can check it itself.

What Claude wrote: the tree test

Open lib/comments.test.ts. First the flat list: two threads, the first with three levels. makeComment is a helper in this file that assembles a comment from an id and a parentId and fills the remaining fields with constants:

// c1 -> c2 -> c3 (three levels) and a separate thread c4
const flat = [
  makeComment("c1", null),
  makeComment("c2", "c1"),
  makeComment("c3", "c2"),
  makeComment("c4", null),
];

The first test checks the shape of the tree: c1 and c4 stand at the top, under c1 is c2, and under it c3. The next two guard the traps from the start of the lesson:

it("a reply stored before its parent still lands under the parent", () => {
  const tree = buildCommentTree([makeComment("c2", "c1"), makeComment("c1", null)]);
  expect(tree.map((c) => c.id)).toEqual(["c1"]);
  expect(tree[0].replies.map((c) => c.id)).toEqual(["c2"]);
});

it("a comment without an existing parent stays at the top instead of vanishing", () => {
  const tree = buildCommentTree([makeComment("c9", "deleted")]);
  expect(tree.map((c) => c.id)).toEqual(["c9"]);
});

toEqual compares whole arrays, so the order of the ids counts too. Read these tests as rules: a reply does not vanish because of its order on the list, and a comment without a parent does not vanish at all. Whether an orphan should stand at the top or disappear is your decision, not the agent's, and the test fixes it.

The simplest version is not enough

The simplest version, which agents often write, builds the tree in one pass: it goes through the list and attaches each comment straight away to the parent it has already seen. We checked it on these tests:

 ❯ lib/comments.test.ts (5 tests | 2 failed) 4ms
   ❯ buildCommentTree (4)
     × a reply stored before its parent still lands under the parent 2ms
     × a comment without an existing parent stays at the top instead of vanishing 0ms

AssertionError: expected [] to deeply equal [ 'c2' ]

      Tests  2 failed | 3 passed (5)

Three tests passed, including the one with three levels. On a screen with sample data everything would look fine. Only the edge cases failed: a reply whose parent stands further down the list disappeared, because at the moment it was read the parent was not there yet. That is what a quietly vanishing bug looks like: no message, just one comment fewer.

What Claude wrote: two passes

After the fix lib/comments.ts has two types. Comment is a comment from the flat list, and CommentNode extends it with the field replies: CommentNode[], that is with children of the same type. The function goes through the list twice:

export function buildCommentTree(comments: Comment[]): CommentNode[] {
  const nodes = new Map<string, CommentNode>();
  for (const comment of comments) {
    nodes.set(comment.id, { ...comment, replies: [] });
  }

Map is a dictionary: by id you get the node straight away, without searching the list. The first pass creates a new node with an empty replies array for every comment. The comments of the input list stay untouched, because every node is a copy made with a spread.

  const roots: CommentNode[] = [];
  for (const node of nodes.values()) {
    const parent = node.parentId ? nodes.get(node.parentId) : undefined;
    if (parent) {
      parent.replies.push(node);
    } else {
      roots.push(node);
    }
  }
  return roots;
}

The second pass already knows all the nodes, so the order on the list does not matter. A node with an existing parent goes into its replies, and every other one, an orphan too, goes to the top level. push changes here the arrays of the new nodes, not the input data. The result of running again:

 Test Files  3 passed (3)
      Tests  18 passed (18)

Test Files 3, because the command runs the tests of the whole project, including voting, sorting and the vote percentage from lesson 4_1. The old code was checked too.

The counter: recursion with an end condition

countTotalComments counts comments on all levels:

export function countTotalComments(nodes: CommentNode[]): number {
  return nodes.reduce((total, node) => total + 1 + countTotalComments(node.replies), 0);
}

reduce goes through the nodes and collects a sum, starting from zero. Every node adds 1 for itself and the result of the same function for its replies. The end condition hides in the empty array: for [] the function returns 0 at once and does not call itself further.

What Claude wrote: a thread that draws itself

When the tests are green, it is time for the screen. The second request says where state lives and where there is only drawing:

Now the screen: the page app/posts/[id]/page.tsx with the post body
and comments. State is held by the flat list in components/CommentSection.tsx,
and buildCommentTree computes the tree on every render.
components/CommentThread.tsx draws the replies recursively, with
indentation up to 4 levels, collapsing a thread and a reply form. The
title on the post card leads to this page. Sample comments in
lib/comment-data.ts: under the first post Morgan, Redbeard replies to
Morgan, Polly to Redbeard, and Jack writes separately. At the end the
tests, lint and build.

The page app/posts/[id]/page.tsx reads id through await params as in lesson 2_1 and passes the post's comments to components/CommentSection.tsx. That section holds the flat list in state and computes the tree on every render:

const [comments, setComments] = useState(initialComments);
const tree = buildCommentTree(comments);

Thanks to this a new reply is one element appended to the end of the list: setComments((prev) => [...prev, comment]), where comment has the parentId of the comment under which Reply was clicked. There is no need to look for the parent deep in the tree or to copy every level. components/CommentThread.tsx draws one comment and under it its replies:

{!isCollapsed &&
  comment.replies.map((reply) => (
    <CommentThread key={reply.id} comment={reply} depth={depth + 1} onReply={onReply} />
  ))}

This is recursion in a component: CommentThread renders CommentThread for every reply, with depth one larger. A comment without replies has an empty array, so map draws nothing and the recursion ends. onReply travels down through all the levels to the form.

depth controls the indentation. The constant MAX_DEPTH = 4 limits it:

const indent = depth > 0 && depth <= MAX_DEPTH;
return (
  <div className={indent ? "ml-4 border-l border-gray-200 pl-3" : ""}>

Up to the fourth level every reply shifts right by ml-4 and gets a vertical line. Deeper replies stand under the parent without further indentation, so a long quarrel does not push the text past the right edge of a phone. Nothing vanishes, only the shifting stops.

Collapsing is state needed only by that one comment, so it lives in it. The [-] button toggles it through setIsCollapsed((prev) => !prev) and has aria-expanded, so a screen reader knows whether the thread is open. A collapsed comment shows the author and a note with the number of hidden replies, computed by countTotalComments(comment.replies).

Captain's review

  1. The end condition. When Claude Code writes a recursive function, first find its end condition. Here it is the empty replies array in the counter and in map.
  2. A deep thread on a phone. Reply several times in a row to the deepest comment and narrow the window to phone width. From the fifth level the indentation stops growing and the text stays readable.
  3. The form really works. Reply to Polly at the deepest level. The reply appears indented under her comment, and the counter above the section rises from 4 to 5. Collapse Morgan's thread: the note says three hidden replies. After a refresh the new reply disappears, because it lives in the browser's state; saving to a database comes in later locations.
  4. Content as text. Send the reply <img src=x onerror=alert(1)>. It must show up as plain text, following the rule from lesson 3_3: zero dangerouslySetInnerHTML in comments.

The typical agent mistake here you already know from the tests: the one-pass version. The second temptation is to keep the tree in state and add replies with comment.replies.push(...) on an object from state. Changing an object React already knows does not refresh the screen and breaks the rule "a new array instead of changing the old one" from lesson 2_3. In the diff look for push on data from state.

Next step

When everything passes, ask for a commit, for example "Comments: a tree from a flat list with tests, threads and collapsing". The next request is small and has boundaries:

For every comment that has replies, show their total number even
when the thread is expanded. Use countTotalComments.
Change only @components/CommentThread.tsx.

If Claude rewrites more than you asked, for example touches CommentSection or the tests, do not patch it with another request. Undo the turn with /rewind from lesson 0_6 and repeat the request in narrower words. In the editor below waits a thread built from a flat list: reply to the deepest comment, collapse the thread and compare the counter of hidden replies.

Remember: you build the thread tree from one flat list, and the test checks that no branch fell off on the way.

Code for this lesson: App.jsx
// Comment threads: a flat list in state, the tree computed on every render
import { useState } from 'react';

const startComments = [
  { id: 'k1', parentId: null, author: 'Morgan', text: 'North. The gold will not wait.' },
  { id: 'k2', parentId: 'k1', author: 'Redbeard', text: 'And what will we quench our thirst with on the way?' },
  { id: 'k3', parentId: 'k2', author: 'Polly', text: 'Rainwater. But there are sharks in the north.' },
  { id: 'k4', parentId: null, author: 'Jack', text: 'Tortuga. We need new hands for the work.' },
  // A reply stored before its parent: two passes will still find it
  { id: 'k6', parentId: 'k5', author: 'Morgan', text: 'The cannons need feeding too.' },
  { id: 'k5', parentId: 'k4', author: 'Polly', text: 'And new barrels of powder.' },
];

const MAX_DEPTH = 4;

function buildCommentTree(comments) {
  // First pass: a node with an empty replies array for every comment
  const nodes = new Map();
  for (const comment of comments) {
    nodes.set(comment.id, { ...comment, replies: [] });
  }
  // Second pass: every node goes under its parent or to the top level
  const roots = [];
  for (const node of nodes.values()) {
    const parent = node.parentId ? nodes.get(node.parentId) : undefined;
    if (parent) parent.replies.push(node);
    else roots.push(node);
  }
  return roots;
}

function countTotalComments(nodes) {
  return nodes.reduce((total, node) => total + 1 + countTotalComments(node.replies), 0);
}

function ReplyForm({ onSubmit, onCancel }) {
  const [text, setText] = useState('');
  const handleSubmit = (event) => {
    event.preventDefault();
    const value = text.trim();
    if (!value) return;
    onSubmit(value);
    setText('');
  };
  return (
    <form onSubmit={handleSubmit} className="mt-2 flex gap-2">
      <input
        value={text}
        onChange={(event) => setText(event.target.value)}
        placeholder="Your reply..."
        aria-label="Reply text"
        className="flex-1 rounded border border-gray-300 px-2 py-1 text-sm"
      />
      <button type="submit" disabled={!text.trim()} className="text-sm font-semibold text-blue-600 disabled:text-blue-300">
        Send
      </button>
      {onCancel && (
        <button type="button" onClick={onCancel} className="text-sm text-gray-500">
          Cancel
        </button>
      )}
    </form>
  );
}

function CommentThread({ comment, depth = 0, onReply }) {
  const [isCollapsed, setIsCollapsed] = useState(false);
  const [isReplying, setIsReplying] = useState(false);
  const hiddenReplies = countTotalComments(comment.replies);
  const indent = depth > 0 && depth <= MAX_DEPTH;

  return (
    <div className={indent ? 'ml-4 border-l border-gray-200 pl-3' : ''}>
      <div className="py-2">
        <p className="text-xs text-gray-500">
          <button
            type="button"
            onClick={() => setIsCollapsed((prev) => !prev)}
            aria-expanded={!isCollapsed}
            aria-label={isCollapsed ? 'Expand thread' : 'Collapse thread'}
            className="mr-1 font-mono"
          >
            {isCollapsed ? '[+]' : '[-]'}
          </button>
          u/{comment.author}
          {isCollapsed && hiddenReplies > 0 && <span> (hidden replies: {hiddenReplies})</span>}
        </p>
        {!isCollapsed && (
          <>
            {/* Content as plain text: React will not run HTML from a comment */}
            <p className="text-sm">{comment.text}</p>
            <button type="button" onClick={() => setIsReplying(true)} className="text-xs text-gray-500 hover:underline">
              Reply
            </button>
            {isReplying && (
              <ReplyForm
                onSubmit={(text) => {
                  onReply(comment.id, text);
                  setIsReplying(false);
                }}
                onCancel={() => setIsReplying(false)}
              />
            )}
          </>
        )}
      </div>
      {!isCollapsed &&
        comment.replies.map((reply) => (
          <CommentThread key={reply.id} comment={reply} depth={depth + 1} onReply={onReply} />
        ))}
    </div>
  );
}

export default function App() {
  const [comments, setComments] = useState(startComments);
  const tree = buildCommentTree(comments);

  // Date.now() only here: this function runs after the form is submitted
  const addComment = (parentId, text) => {
    const comment = { id: String(Date.now()), parentId, author: 'You', text };
    setComments((prev) => [...prev, comment]);
  };

  return (
    <div className="min-h-screen bg-gray-100 p-4 text-gray-900">
      <div className="mx-auto max-w-xl rounded-lg bg-white p-4">
        <h1 className="text-xl font-bold">Sail to Tortuga or head north?</h1>
        <h2 className="mt-4 font-bold">Comments ({comments.length})</h2>
        <ReplyForm onSubmit={(text) => addComment(null, text)} />
        {tree.map((node) => (
          <CommentThread key={node.id} comment={node} onReply={addComment} />
        ))}
      </div>
    </div>
  );
}

Spotted a mistake in this lesson?

Check yourself

Answer the questions from this lesson. Pick an answer to see right away whether it is correct.

  1. 1. Why does CommentNode have a 'replies: CommentNode[]' field?

  2. 2. How do you render nested comments?

These are 2 of 7 questions for this lesson. Solve the rest in the game.

Hands-on tasks in the game

  • Code editor

    Threaded comments

  • Vertical ordering

    The flat list has, in order: Morgan (parentId null), Redbeard (replies to Morgan), Polly (replies to Redbeard), Jack (parentId null). Arrange the comments as CommentThread shows them from the top of the screen:

  • Click in order

    Build the type of the replies field in the CommentNode interface by clicking the tokens in order:

  • Code editor

    Collapse comment thread

  • Vertical ordering

    Order the steps of the buildCommentTree function from the lesson:

  • Horizontal ordering

    Arrange the call that counts all replies under a comment, on all levels (one line, left to right):

  • Vertical ordering

    Order the comments by increasing nesting depth:

  • Click in order

    Build the recursive reply-rendering call by clicking the tokens in order:

  • Vertical ordering

    Order what happens after a reply is sent under Polly's comment:

  1. QuestionQuiz: The replies field in CommentNode
  2. QuestionQuiz: Recursive component
  3. QuestionQuiz: Depth and indentation
  4. Coding taskPractice: Comment thread
  5. Put in orderSorting: The order of a thread on screen
  6. QuestionQuiz: The MAX_DEPTH indentation limit
  7. Click in orderSequence: replies type
  8. Coding taskPractice: Collapse/Expand
  9. QuestionQuiz: Collapse/Expand
  10. QuestionQuiz: Counting comments
  11. Put in orderSorting: buildCommentTree step by step
  12. QuestionQuiz: Two passes of buildCommentTree
  13. Put in orderSorting: The number of hidden replies
  14. Put in orderSorting: Nesting depth
  15. Click in orderSequence: Render replies
  16. Put in orderSorting: The path of a new reply

Useful articles