LESSON 03 / 03

Server vs Client Components

The big idea of modern Next.js: components run on the server by default (fast, secure, can read databases) and you opt into the browser with "use client" only where you need interactivity.

๐ŸŽ“Mediumlevel
โฑ๏ธ40 minto finish
โœ๏ธ2activities

๐Ÿ“‚ Next.js Foundations๐Ÿท๏ธ Next.js

๐ŸŽฏ 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}
Where should it run?
Needsโ€ฆServer componentClient 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.