Vibe coding with Claude Code course · Module 10: TikTok clone

The For You Feed: One Clip per Screen, Checked by Ear

9 min read
In this lesson11

Ahoy! The crew films short clips from every expedition: a chest under a palm, a boarding at dawn, the shadow of a kraken under the water. Today those clips vanish into a folder on the ship's computer. In this location you build Treasure Reels, a TikTok clone: vertical full-screen clips, scrolled one after another with a thumb, with sounds, a recorder, duets and an editor. You start with the heart of the app, the feed.

What you will learn

  • create the Treasure Reels project and order the feed with a plan built from a screenshot;
  • read in Cursor the code that decides which clip plays and which one stands still;
  • check behaviour in the browser, not just looks: scroll and listen;
  • recognise the three mistakes an agent makes most often with video.

A new port: the treasure-reels project

Treasure Reels is a separate app, so you create it with the command from lesson 1_2, changing only the name. Before you click Yes, compare the command with this one:

npx create-next-app@latest treasure-reels --ts --eslint --tailwind --app --no-src-dir --no-cache-components --agents-md --no-agent-feedback --use-npm

Then the familiar routine: a session in the treasure-reels folder, a CLAUDE.md that imports @AGENTS.md, Vitest with the @types/node fix from lesson 4_1, and a first commit. For the feed you also need a few short clips with sound in public/videos/. Film four vertical shots of a few seconds with your phone or, if you have the ffmpeg program, ask Claude for four test clips, each with a different tone of sound. A different tone in each clip helps during the review, because you will hear which clip is playing.

A plan from a screenshot

A feed is easier to show than to describe. Take a screenshot of any app with short clips and save it as sketches/feed.png, like the sketches in location 4. Then start with a plan, because with video most mistakes hide in what the screenshot does not show.

Request for Claude Code:

/plan Build a vertical feed in Treasure Reels like sketches/feed.png:
one clip per full screen, thumb scrolling that snaps to a clip, an
overlay with the author, caption, hashtags, sound and counters. Types
in types/video.ts, data in lib/videos.ts from the clips in
public/videos, components ForYouFeed and VideoInfoOverlay. Write in
the plan what happens to a clip that scrolled off the screen and what
happens when the browser will not let a clip play with sound. Do not
write code yet.

The last two questions are the hooks. A good plan answers: a clip off the screen stops and goes back to the start, and the feed starts muted and has a button that turns the sound on. A plan that says nothing about it, you fix before you approve it, not after the build.

What Claude wrote: the types

Open types/video.ts in Cursor. A sound and a clip have one type each, used by the whole app:

export interface Sound {
  id: string;
  title: string; // "Pirate Anthem"
  author: string;
}

export interface Video {
  id: string;
  src: string; // "/videos/captain.mp4"
  poster: string; // the first frame as an image
  author: { username: string; verified: boolean };
  caption: string;
  hashtags: string[];
  sound: Sound;
  likes: number;
  comments: number;
  shares: number;
}

poster is the image the browser shows before a clip loads. sound is not a string but an object of type Sound, because in the next lesson the sound library will extend exactly this type instead of writing a second, similar one. Two types of the same sound start to differ after a while, and the compiler has no way to notice.

What Claude wrote: the counters

The numbers on the overlay pass through one function in lib/format.ts:

const compact = new Intl.NumberFormat("en-US", {
  notation: "compact",
  maximumFractionDigits: 1,
});

export function formatCount(count: number): string {
  return compact.format(count);
}

Intl.NumberFormat is the number formatter built into the browser, and notation: "compact" shortens large values for the chosen language. Here our check printed 999 as "999", 1500 as "1.5K" and 2,340,000 as "2.3M". The same formatter with the pl-PL locale glues the abbreviation to the number with a no-break space, and tests that compare it with a normal space fail on identical-looking strings. The English output has no space at all, but the lesson stays the same: the locale changes the characters, so a test should read them from the formatter or match them loosely.

What Claude wrote: which clip is on the screen

Open components/ForYouFeed.tsx. The container has the classes snap-y snap-mandatory overflow-y-scroll and every slide has h-dvh snap-start: scrolling always stops at the start of a clip. Which clip fills the screen is told by an intersection observer, the IntersectionObserver built into the browser, a watchman that reports when an element appears in view:

useEffect(() => {
  const observer = new IntersectionObserver(
    (entries) => {
      for (const entry of entries) {
        if (entry.isIntersecting) {
          setActive(Number((entry.target as HTMLElement).dataset.index));
        }
      }
    },
    { threshold: 0.6 },
  );
  slideRefs.current.forEach((slide) => slide && observer.observe(slide));
  return () => observer.disconnect();
}, [videos]);

threshold: 0.6 means a slide counts as active when at least 60% of its height is visible. The slide number sits in the data-index attribute. The state changes inside the observer's callback, not straight in the body of the effect, so the lint rule react-hooks/set-state-in-effect, which rejects state set directly in an effect, has nothing to complain about. disconnect() in the cleanup detaches the watchman when the feed leaves the page.

What Claude wrote: only one plays

When the active clip changes, a second effect walks through all the <video> elements:

useEffect(() => {
  videoRefs.current.forEach((video, i) => {
    if (!video) return;
    if (i === active) {
      video.play().then(
        () => setBlocked(false),
        () => setBlocked(true),
      );
    } else {
      video.pause();
      video.currentTime = 0;
    }
  });
}, [active]);

The active clip gets play(), every other one gets pause() and goes back to the start. According to MDN, play() returns a promise, and a browser that does not allow playback without a user gesture rejects it with a NotAllowedError. MDN advises that the interface should not assume playback has started. That is why the second argument of then sets blocked, and a "Tap to play" button appears on the clip. The clips start with muted and playsInline: according to the MDN autoplay guide, muted sound or an earlier interaction with the page are the conditions under which browsers usually allow playback. An "Unmute" button in the corner removes the mute after a click, which is an interaction.

What Claude wrote: references to the clips

The effect needs access to every <video> element, so Claude keeps them in an array inside useRef, and every element writes itself into it with a ref function:

<video
  ref={(el) => {
    videoRefs.current[i] = el;
  }}

The curly braces are not decoration. The shorter form ref={(el) => (videoRefs.current[i] = el)} returns the assigned value, and in React 19 a ref function may return only nothing or a cleanup function. For us npx tsc --noEmit rejected the shorter version with TS2322 and the line Type 'HTMLVideoElement | null' is not assignable to type 'void | (() => VoidOrUndefinedOnly)', while npm run lint did not notice it.

What Claude wrote: not everything at once

Four clips are nothing, but a feed with a hundred clips cannot download them all at the start:

preload={Math.abs(i - active) <= 1 ? "auto" : "none"}

The preload attribute tells the browser what to fetch before playback: none nothing, auto the whole file. MDN adds that it is only a hint the browser may ignore. For us the browser downloaded only the first and second clip at the start, and the third only after we scrolled to the second. The poster images arrived for all four, because they are small.

Captain's review

  1. Pausing the previous clip. A typical agent mistake is an effect with the single line videoRefs.current[active]?.play(). That version passed lint, tsc and the build for us, and after scrolling to the third clip two played at once: the first still in the background and the third on screen. You search the file (Cmd+F on a Mac, Ctrl+F on Windows) for the word pause, and then you check by ear: scroll three clips and listen whether you hear one tone.
  2. The promise from play(). Every play() has a rejection handler. Whether your browser blocks sound depends on its rules and on your history with the page, so the code must handle both outcomes.
  3. A key from the id. The slides have key={video.id}, not the index from map. When the feed gets new clips at the top, React with an index key would reuse the old <video> for a different clip.
  4. Counters through formatCount. Search the project (Cmd+Shift+F) for .likes} and .comments}: a raw number on the screen is a sign the formatter was skipped.
  5. Proof. Ask for a test with a fake player like in lesson 4_1: after the active slide changes, the previous clip gets pause(), and a rejected play() shows the button. For us the version with the mistake from point 1 failed both tests. Then npm run lint, npx tsc --noEmit and npm run build.

Next step

If the review found something, the fix goes in one narrow request, for example: "In @components/ForYouFeed.tsx clips off the screen must stop and go back to the start. Change nothing else. Then tests and lint." The diff in the Source Control panel should show a change in one effect, nothing more. When everything plays, or rather one thing plays at a time, ask for a commit, for example "For You feed with overlay".

In the editor below a miniature feed is waiting, with fake clips that count seconds. Scroll, like a clip and turn on the agent bug to see how many clips play at once.

Remember: a captain does not judge a chest by how it shines but opens it and checks what is inside, and a feed is checked by ear, not by eye.

Code for this lesson: App.jsx
// For You feed in miniature: fake clips count seconds instead of playing
import { useEffect, useState } from 'react';

const clips = [
  { id: 'v1', author: 'captain_redbeard', caption: 'Chest under the palm', sound: 'Pirate Anthem', likes: 125400, color: 'from-sky-900 to-blue-700' },
  { id: 'v2', author: 'black_mary', caption: 'Boarding at dawn', sound: 'Battle Drums', likes: 1500, color: 'from-red-900 to-orange-700' },
  { id: 'v3', author: 'map_hunter', caption: 'Map to Isla de Muerta', sound: 'Shanty of the Island', likes: 2340000, color: 'from-emerald-900 to-teal-700' },
  { id: 'v4', author: 'deckhand_tom', caption: 'Something stirs under the water', sound: 'Pirate Anthem', likes: 999, color: 'from-purple-900 to-fuchsia-700' },
];

const compact = new Intl.NumberFormat('en-US', { notation: 'compact', maximumFractionDigits: 1 });
const formatCount = (n) => compact.format(n);

export default function App() {
  const [active, setActive] = useState(0);
  const [playing, setPlaying] = useState(() => new Set([0]));
  const [loaded, setLoaded] = useState(() => new Set([0, 1]));
  const [seconds, setSeconds] = useState({});
  const [liked, setLiked] = useState(() => new Set());
  const [agentBug, setAgentBug] = useState(false);
  const [autoplayBlocked, setAutoplayBlocked] = useState(false);
  const [blocked, setBlocked] = useState(false);
  const [muted, setMuted] = useState(true);

  // Clock of the fake clips: every second it adds time to each clip that is playing.
  useEffect(() => {
    const id = setInterval(() => {
      setSeconds((prev) => {
        const next = { ...prev };
        playing.forEach((i) => { next[i] = (next[i] || 0) + 1; });
        return next;
      });
    }, 1000);
    return () => clearInterval(id);
  }, [playing]);

  function goTo(index) {
    if (index < 0 || index >= clips.length) return;
    setActive(index);
    setLoaded((prev) => new Set([...prev, index - 1, index, index + 1].filter((i) => i >= 0 && i < clips.length)));
    // play() rejected by the browser (NotAllowedError)
    if (autoplayBlocked) {
      setBlocked(true);
      setPlaying((prev) => (agentBug ? prev : new Set()));
      return;
    }
    setBlocked(false);
    if (agentBug) {
      // agent bug: only play() for the new clip, no pause() for the old ones
      setPlaying((prev) => new Set([...prev, index]));
    } else {
      setPlaying(new Set([index]));
      setSeconds((prev) => {
        const next = { ...prev };
        clips.forEach((_, i) => { if (i !== index) next[i] = 0; });
        return next;
      });
    }
  }

  function toggleLike(id) {
    setLiked((prev) => {
      const next = new Set(prev);
      if (next.has(id)) next.delete(id);
      else next.add(id);
      return next;
    });
  }

  const clip = clips[active];
  const likes = clip.likes + (liked.has(clip.id) ? 1 : 0);

  return (
    <div className="min-h-screen bg-gray-950 text-white p-4 flex flex-col md:flex-row gap-4">
      <div className={`relative mx-auto h-[480px] w-[270px] rounded-2xl bg-gradient-to-b ${clip.color} overflow-hidden`}>
        <p className="absolute top-3 left-3 rounded-full bg-black/50 px-3 py-1 text-xs">
          {playing.has(active) ? `▶ playing ${seconds[active] || 0} s` : '⏸ paused'}
        </p>
        <button
          type="button"
          onClick={() => setMuted((m) => !m)}
          className="absolute top-3 right-3 rounded-full bg-black/50 px-3 py-1 text-xs"
        >
          {muted ? 'Unmute' : 'Mute'}
        </button>
        {blocked && (
          <button
            type="button"
            onClick={() => { setBlocked(false); setPlaying((prev) => new Set([...prev, active])); }}
            className="absolute inset-0 m-auto h-12 w-48 rounded-full bg-black/70 text-sm"
          >
            Tap to play
          </button>
        )}
        <div className="absolute right-3 bottom-24 flex flex-col items-center gap-1">
          <button type="button" aria-pressed={liked.has(clip.id)} onClick={() => toggleLike(clip.id)} className="text-3xl">
            <span className={liked.has(clip.id) ? 'text-red-500' : 'text-white'}>♥</span>
          </button>
          <span className="text-xs font-semibold">{formatCount(likes)}</span>
        </div>
        <div className="absolute bottom-4 left-3 right-14">
          <p className="font-bold">@{clip.author}</p>
          <p className="text-sm">{clip.caption}</p>
          <p className="mt-1 inline-block rounded-full bg-black/40 px-2 py-1 text-xs">♪ {clip.sound}</p>
        </div>
      </div>

      <div className="flex-1 space-y-3 text-sm">
        <div className="flex gap-2">
          <button type="button" onClick={() => goTo(active - 1)} disabled={active === 0} className="rounded bg-gray-700 px-4 py-2 disabled:opacity-40">▲ Previous</button>
          <button type="button" onClick={() => goTo(active + 1)} disabled={active === clips.length - 1} className="rounded bg-gray-700 px-4 py-2 disabled:opacity-40">▼ Next</button>
        </div>
        <p>Clip {active + 1} of {clips.length}. Playing now: <strong>{playing.size}</strong></p>
        <ul className="space-y-1">
          {clips.map((c, i) => (
            <li key={c.id} className={i === active ? 'text-yellow-300' : 'text-gray-300'}>
              {i + 1}. {c.caption}: {playing.has(i) ? `playing (${seconds[i] || 0} s)` : 'paused'}, {loaded.has(i) ? 'loaded' : 'waiting (preload none)'}
            </li>
          ))}
        </ul>
        <label className="flex items-center gap-2">
          <input type="checkbox" checked={agentBug} onChange={(e) => setAgentBug(e.target.checked)} />
          Agent bug: only play(), no pause()
        </label>
        <label className="flex items-center gap-2">
          <input type="checkbox" checked={autoplayBlocked} onChange={(e) => setAutoplayBlocked(e.target.checked)} />
          The browser rejects play() (NotAllowedError)
        </label>
      </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. What should happen in the Treasure Reels feed to a clip that scrolled off the screen?

  2. 2. Why does the feed plan request ask about a clip off the screen and about blocked sound?

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

Hands-on tasks in the game

  • Code editor

    TikTok-style feed

  • Horizontal ordering

    Put the line in order that makes the browser download only the active clip and its neighbours:

  • Click in order

    Build the statement that rewinds a stopped clip to the start (click in order):

  • Code editor

    Video overlay component

  • Vertical ordering

    Put the work on the feed from the lesson in order (from the first step):

  • Horizontal ordering

    Put the line in order that hands all the feed's slides to the watchman:

  1. QuestionClip off the screen
  2. QuestionHooks in the plan request
  3. QuestionA rejected play()
  4. Coding taskPractice: Vertical video feed
  5. Put in orderThe preload attribute in the feed
  6. QuestionBraces in the ref function
  7. Click in orderBack to the start
  8. QuestionIntersectionObserver in the feed
  9. Coding taskPractice: Video info overlay
  10. Put in orderFrom screenshot to a check by ear
  11. QuestionThe formatCount function
  12. QuestionThe poster field in Video
  13. Put in orderWatching the slides

Useful articles