๐ฏ By the end of this lesson you canโฆ
- Explain server and client components
- Decide where "use client" belongs
- Pass data from server to client components
โ๏ธ JSX
app/notes/page.jsx
๐ Tap a line to explain it
1import LikeButton from "./LikeButton";2import { db } from "@/lib/db";3 4export default async function NotesPage() {5 const notes = await db.note.findMany();6 return (7 <ul>8 {notes.map((n) => (9 <li key={n.id}>10 {n.title} <LikeButton initialLikes={n.likes} />11 </li>12 ))}13 </ul>14 );15}
โ๏ธ JSX
app/notes/LikeButton.jsx
๐ Tap a line to explain it
1"use client";2import { useState } from "react";3 4export default function LikeButton({ initialLikes }) {5 const [likes, setLikes] = useState(initialLikes);6 return <button onClick={() => setLikes(likes + 1)}>๐ {likes}</button>;7}
| Needsโฆ | Server component | Client component |
|---|---|---|
| Database / secret keys | โ | โ never |
| useState, useEffect, onClick | โ | โ |
| Browser APIs (localStorage, window) | โ | โ |
| Large libraries (markdown, dates) | โ (not shipped to users) | adds to bundle size |
๐ก Concept check
A component shows a list from the database and has no buttons. Where should it run?
๐ Find the error
This file crashes with “useState only works in Client Components”. Fix?
1import { useState } from "react";2export default function Counter() {3 const [n, setN] = useState(0);4 return <button onClick={() => setN(n + 1)}>{n}</button>;5}
๐ Key takeaways
- Components are server components by default: they can be async and read data directly.
- Add
"use client"only for interactivity: state, effects, event handlers, browser APIs. - Keep client components small (leaves of the tree) โ less JavaScript sent to the browser.
Finished reading & practising?
Saved in this browser. Create a free account to keep it forever.