Vibe coding with Claude Code course ยท Module 3: Twitter clone

The logbook: state, likes and a new post

10 min read ยท
In this lesson8

The messenger looks like a real one but nothing in it reacts. The like button stands still, and a new post cannot be added. The simplest idea, a plain variable in the component, will not work:

function LikeButton() {
  let likes = 0;

  return (
    <button onClick={() => { likes++; console.log(likes); }}>
      Like ({likes})
    </button>
  );
}

The console will show 1, 2, 3, but on the screen it stays 0. React does not know the variable changed, so it does not draw the component again. And if it did, likes would start from zero again, because on every render the component function runs from the beginning. You need memory that survives between renders, and a signal "the data changed, refresh the screen".

useState in one line

useState, a React hook, gives you both. A hook is a function with the use prefix that you call at the top level of a component, not inside a condition or a loop. Think of the logbook: the captain writes the state of the ship in it, and every new entry is a sign for the crew that something has changed. The whole declaration fits in one line:

const [count, setCount] = useState(0);

useState(0) creates state with the initial value 0 and returns an array of two elements: count is the current value, and setCount is the setter, a function that changes it. Calling setCount(count + 1) stores the new value and tells React to draw the component once more. The setter does not change the variable right away: in the current call count still has the old value, and the new one appears in the next render. State works in the browser, so a file with it starts with "use client" from lesson 2_2.

Request for Claude Code

The feature touches four files and leaves choices open, for example where to keep the posts and how to save them, so you start with a plan, as in lesson 2_1.

Request for Claude Code:

/plan Bring the messenger feed to life. 1) The like button as a separate
Client Component in components/LikeButton.tsx; the number starts from
the likes prop of @components/Post.tsx. 2) Above the posts from
@lib/posts.ts a new post form with a textarea; the captain's new post
lands on top, with the time it was added. 3) New posts are saved in
localStorage and come back after a refresh. "use client" only in files
with state, Post stays without the directive. After every step run
npm run build and npm run lint.

The plan should name the new files components/LikeButton.tsx and components/Feed.tsx and the changes in components/Post.tsx and app/feed/page.tsx. Approve it with Yes, manually approve edits and read every edit.

What Claude wrote: the like button

Open components/LikeButton.tsx. This is the whole file:

"use client";

import { useState } from "react";

interface LikeButtonProps {
  initialLikes: number;
}

export default function LikeButton({ initialLikes }: LikeButtonProps) {
  const [likes, setLikes] = useState(initialLikes);

  return (
    <button
      type="button"
      onClick={() => setLikes(likes + 1)}
      className="mt-3 text-sm text-gray-500 hover:text-red-600"
    >
      Like ({likes})
    </button>
  );
}

onClick reacts to a click, and the setter raises the number. The initialLikes prop does not change: it only gives the starting value, and from then on the likes state lives its own life. In Post.tsx the old button was replaced by the line <LikeButton initialLikes={likes} />, and Post itself still has no directive. So only the button code goes to the browser, as lesson 2_2 advised.

What Claude wrote: the feed with a form

Open components/Feed.tsx. At the top of the file Claude described the post from the form and the function that reads the saved posts:

interface CrewPost {
  id: string;
  content: string;
  createdAt: string;
}

const STORAGE_KEY = "kraken-posts";

function loadPosts(): CrewPost[] {
  const saved = localStorage.getItem(STORAGE_KEY);
  return saved ? JSON.parse(saved) : [];
}

localStorage is a small store in the browser that keeps text under keys. You turn an array into text with JSON.stringify and back with JSON.parse. Note createdAt: string: the time of adding is text in the ISO format, for example 2026-11-14T09:30:00.000Z. Why not Date the captain's review will explain.

The component begins with one guard and two pieces of state:

use(browser("Posts from the form are saved in localStorage."));

const [posts, setPosts] = useState<CrewPost[]>(loadPosts);
const [draft, setDraft] = useState("");

posts is the array of posts, and draft is the content of the field. At the top of the file stand the imports use, useEffect and useState from react and browser from react-dom. Instead of an initial value, useState got the function loadPosts: React calls it once, on the first render, so the saved posts are in place before anything appears on screen. The first line is new in React 19.3: use(browser(...)) says "draw this component only in the browser". Next.js renders Client Components on the server at build too, and there localStorage does not exist. Without this line the build ends with ReferenceError: localStorage is not defined. If Claude does not know this pattern, ask it to look in the documentation in node_modules/next/dist/docs/, as AGENTS.md tells it to.

The form and the new post on top

Claude wired the form field to the draft state. In short, without the Tailwind classes, it looks like this:

<form onSubmit={handleSubmit}>
  <textarea value={draft} onChange={(e) => setDraft(e.target.value)} rows={3} />
  <button type="submit">Send</button>
</form>

This is a controlled form: the field shows the value from state (value), and onChange stores every change through e.target.value. Thanks to that you always know what is in the field, and you clear it with one setter. Sending is handled by the handleSubmit function:

const handleSubmit = (e: React.SubmitEvent<HTMLFormElement>) => {
  e.preventDefault();
  if (!draft.trim()) return;

  const newPost: CrewPost = {
    id: String(Date.now()),
    content: draft.trim(),
    createdAt: new Date().toISOString(),
  };

  setPosts([newPost, ...posts]);
  setDraft("");
};

After a form is submitted the browser by default reloads the page, and then all state is lost; e.preventDefault() blocks that. The type React.SubmitEvent<HTMLFormElement> describes exactly this form submit event. trim() cuts the spaces, so an empty post will not be sent. setPosts([newPost, ...posts]) creates a new array: the new post at the start, and ...posts, the spread operator, copies the old elements after it. The old array stays untouched, and React gets a new one and knows the screen has to be refreshed. Claude displays every post with the Post component, which got an optional time prop with the value new Date(post.createdAt).toLocaleTimeString("en-US"): the text turns into a date only when displayed.

The effect: saving after every change

Saving is left. One effect takes care of it:

useEffect(() => {
  localStorage.setItem(STORAGE_KEY, JSON.stringify(posts));
}, [posts]);

Writing to localStorage is a side effect: something the component does besides drawing the screen. useEffect is for that. React runs the effect after a render, and the second argument, the dependency array, says when. [posts] means "after the first render and after every render in which the posts array changed", the empty array [] runs the effect once, after the first render, that is, when the component mounts, and no array at all means after every render. In development mode the App Router turns on Strict Mode, which runs every effect one extra time to catch bugs; a double save of the same posts breaks nothing.

In app/feed/page.tsx Claude wrapped <Feed /> in <Suspense fallback={<p>Loading your posts...</p>}>. At build the server leaves the fallback text there, and the browser swaps it for the form and the posts. Without this guard the build breaks too. The feed page stays a Server Component: the posts from lib/posts.ts come from the server, and only Feed runs in the browser. Posts from the form have no "Open post" link, because they live only in your browser and the server does not know them.

Captain's review

Add two posts, click a few likes, refresh the page and check:

  1. The time after a refresh. A typical agent mistake is createdAt: Date in the interface and new Date() when creating the post. Before the refresh everything works, and after it Next.js shows this error:
Runtime TypeError
post.createdAt.toLocaleTimeString is not a function

JSON.stringify turned the date into text, and JSON.parse does not turn it back, so the state holds a string, not a Date. TypeScript will not catch it, because JSON.parse returns the type any, which the compiler takes on faith: the build and lint pass. The fix is an ISO string in the interface and new Date(...) only when displaying, as in the code above. In the diff look for the word Date in the types of data that go to localStorage.

  1. A copy, not a mutation. The code has no posts.push(newPost) or post.likes++. push changes the existing array and does not call the setter, and even setPosts(posts) after it does nothing, because React gets the same array and decides nothing has changed.
  2. State in the right component. The number of likes is needed only by the button, so it lives in LikeButton. The posts are needed by both the form and the list, so they live in their shared parent, Feed. A common mistake: Claude splits Feed into CreatePostForm and PostList, each with its own useState of posts, and the form adds to an array the list cannot see. The cure is called lifting state up: state goes up, to the parent:
<CreatePostForm onAdd={(newPost) => setPosts([newPost, ...posts])} />
<PostList posts={posts} />

Data flows down as props, and changes go up through a function: the form does not change state itself, it only calls onAdd, and the parent updates the array and both children get the same one.

  1. Lint without silencing. If Claude loads the posts in useEffect through setPosts, npm run lint reports the react-hooks/set-state-in-effect rule. Do not agree to an eslint-disable comment, ask for loading in useState(loadPosts) instead.

Next step

When the list passes, ask for a commit with a message like "Feed: likes, post form and saving in localStorage". If Claude rewrote half of the feed on the way, /rewind with the Restore code option goes back to the state before the request. Then a small extension:

Add a character counter like "12/280" under the field in
@components/Feed.tsx. The limit is 280 characters, the counter turns
red above 90% of the limit, and the Send button is disabled for an
empty and for a too long post. Change nothing else.

The counter needs no new state, because the number of characters can be computed from draft.length on every render. If Claude adds a separate useState for the counter, ask why. In the editor below waits a feed you can click through: like a post, add a new one and click "Reload" to see that the time survived the save as text.

Remember: state is the component's logbook, and you carry the date ashore as text and turn it into a calendar only when you read it.

Code for this lesson: App.jsx
// The messenger feed: likes, a new post form and saving to localStorage.
// In Next.js you render this component only in the browser: use(browser()) and <Suspense>.
// There is no server here, so localStorage is available right away.
import { useEffect, useState } from 'react';
import Post from './components/Post';

const STORAGE_KEY = 'kraken-posts';

// The crew posts that live in lib/posts.ts in the project
const crewPosts = [
  { id: '1', author: 'Anne Bonny', avatar: 'AB', content: 'Kraken spotted near Skull Island. Sailing west.', likes: 12 },
  { id: '2', author: 'Jack Rackham', avatar: 'JR', content: 'Rudder fixed. Who will help with the sails?', likes: 5 },
];

function loadPosts() {
  const saved = localStorage.getItem(STORAGE_KEY);
  return saved ? JSON.parse(saved) : [];
}

export default function App() {
  // Lazy start: loadPosts runs once, on the first render
  const [posts, setPosts] = useState(loadPosts);
  const [draft, setDraft] = useState('');

  // Save after the first render and after every change of posts
  useEffect(() => {
    localStorage.setItem(STORAGE_KEY, JSON.stringify(posts));
  }, [posts]);

  const handleSubmit = (e) => {
    e.preventDefault();
    if (!draft.trim()) return;

    const newPost = {
      id: String(Date.now()),
      content: draft.trim(),
      createdAt: new Date().toISOString(), // an ISO string, not a Date object
    };

    setPosts([newPost, ...posts]); // a new array, the new post on top
    setDraft('');
  };

  // Pretends to refresh the page: posts come back from localStorage through JSON.parse
  const reload = () => setPosts(loadPosts());

  return (
    <div className="min-h-screen bg-gray-50 p-6 text-gray-900">
      <h1 className="text-3xl font-bold">Crew feed</h1>

      <form onSubmit={handleSubmit} className="mt-4 rounded-lg border border-gray-300 bg-white p-4">
        <textarea
          value={draft}
          onChange={(e) => setDraft(e.target.value)}
          rows={3}
          placeholder="What's new on deck?"
          className="w-full rounded border border-gray-300 p-2"
        />
        <div className="mt-2 flex gap-2">
          <button type="submit" className="rounded bg-blue-600 px-4 py-2 font-semibold text-white">
            Send
          </button>
          <button type="button" onClick={reload} className="rounded border border-gray-300 px-4 py-2">
            Reload
          </button>
        </div>
      </form>

      <ul className="mt-4 space-y-4">
        {posts.map((post) => (
          <li key={post.id}>
            <Post
              author="Captain Redbeard"
              avatar="KR"
              content={post.content}
              likes={0}
              time={new Date(post.createdAt).toLocaleTimeString('en-US')}
            />
          </li>
        ))}
        {crewPosts.map((post) => (
          <li key={post.id}>
            <Post author={post.author} avatar={post.avatar} content={post.content} likes={post.likes} />
          </li>
        ))}
      </ul>

      <details className="mt-6 text-sm">
        <summary className="cursor-pointer">What is in localStorage</summary>
        <pre className="mt-2 whitespace-pre-wrap break-all rounded bg-gray-900 p-3 text-green-300">
          {JSON.stringify(posts, null, 2)}
        </pre>
      </details>
    </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 does useState(0) return?

  2. 2. What is the second value in the useState array, e.g. setCount?

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

Hands-on tasks in the game

  • Code editor

    Write a Counter component (export default), a loot counter. Add 'use client' at the top of the file. Keep the number in a count state with useState(0), display it, and add a +1 button next to it that increases the counter by 1 on every click.

  • Horizontal ordering

    Arrange the tokens of a counter state declaration:

  • Click in order

    Click the tokens to block the page reload:

  • Horizontal ordering

    Arrange the tokens that increase the counter by one:

  • Code editor

    Write a CreatePostForm component (export default), a form for the captain's logbook. Add 'use client' at the top of the file. Inside a form tag put a textarea whose content you keep in useState (value and onChange) and a submit button (a button of type submit). In onSubmit call e.preventDefault() and clear the field.

  • Click in order

    Click the tokens to update state with the input's value:

  • Vertical ordering

    Arrange what happens after a form is submitted:

  • Horizontal ordering

    Arrange the tokens that turn the saved createdAt text into a time to display:

  • Click in order

    Click the tokens to add a new post to the front of the list:

  • Vertical ordering

    Arrange the steps of moving state up to the parent:

  • Code editor

    Write a Feed component (export default) that connects the form to the list of posts. Add 'use client' at the top of the file. Keep the posts in an array state with useState and the new post's text in a separate state bound to a textarea (value and onChange). When the form is submitted, call e.preventDefault(), add the new post to the top of the list and clear the field. Render the posts with map() and a key prop.

  • Click in order

    Click the tokens to start a useEffect that runs once:

  • Vertical ordering

    Arrange what happens to the posts from opening the feed to saving:

  1. QuestionQuiz: useState
  2. QuestionThe second value from useState
  3. Coding taskPractice: Counter with useState
  4. Put in orderuseState declaration
  5. QuestionAdding to array state
  6. QuestionQuiz: Forms
  7. Click in orderBuild e.preventDefault()
  8. Put in orderCalling the state setter
  9. Coding taskPractice: Post form
  10. QuestionUpdating an input
  11. Click in orderBuild a state update from an input
  12. Put in orderForm submission flow
  13. Put in orderTime from an ISO string
  14. Click in orderBuild adding to array state
  15. QuestionLifting state up
  16. Put in orderLifting state up steps
  17. Coding taskPractice: Feed with dynamic posts
  18. QuestionQuiz: useEffect
  19. QuestionuseEffect dependency array
  20. Click in orderBuild a useEffect call
  21. Put in orderPersistence of posts in localStorage
  22. QuestionSaving to localStorage

Useful articles