Lesson 4
Components
7 min read
Imagine a course page with six lesson cards. In plain HTML you would copy the same block of markup six times and change the text in each. If you later want to add an icon, you have to edit all six. React components fix this: you write the card once, give it a name, and use it as many times as you like.
Your first component
A component is a JavaScript function whose name starts with a capital letter and which returns JSX. You use it like a new HTML tag.
type LessonCardProps = {
title: string;
minutes: number;
};
export function LessonCard({ title, minutes }: LessonCardProps) {
return (
<article className="card">
<h2>{title}</h2>
<p>{minutes} min read</p>
</article>
);
}The values passed into a component are called props, short for properties. They work like HTML attributes. Curly braces { } inside JSX mean "put a JavaScript value here", so {title} prints whatever title the card was given.
import { LessonCard } from "./components/LessonCard";
export default function HomePage() {
return (
<main>
<LessonCard title="What is Node.js?" minutes={6} />
<LessonCard title="Pages and routes" minutes={8} />
</main>
);
}Server and Client Components
In Next.js, components are Server Components by default. They run on the server (or during the build), send finished HTML to the browser, and add no JavaScript of their own. That keeps pages fast, and it lets them safely read files or databases.
Some components need to react to clicks or typing, like a menu button or a "mark complete" toggle. Those must run in the browser. You mark them by writing "use client" at the very top of the file. Only then can you use interactive features such as useState and onClick. Client Components are still rendered to HTML on the server first, so browser-only tools like localStorage must be used inside useEffect or an event handler, which only run in the browser.
Thinking in components changes how you look at a design. Before writing any code, try drawing boxes around the repeated parts of a page: the header, each card, the footer. Each box is a component waiting to be written. Next, you will fill those components with real data.