Lesson 3 of 10 · Own the code AI writes
React components explained read one line by line
React components explained for people who didn't write them: props, state, Server and Client Components, and the question to ask of every line.
Ask an AI tool for a page and you'll get React components back. A component is a function that returns a piece of the page: a button, a form, a whole screen. Learn to read one and you can read most of what these tools write.
This lesson takes one apart. It's a sign-up form of the kind an AI writes every day, in a Next.js app. Read the whole thing once without worrying about the parts you don't follow, then we'll go through it.
"use client";
import { useState } from "react";
type Props = {
title: string;
buttonLabel?: string;
};
export default function SignupForm({ title, buttonLabel = "Sign up" }: Props) {
const [email, setEmail] = useState("");
const [status, setStatus] = useState("idle");
async function send() {
setStatus("sending");
try {
const response = await fetch("/api/subscribe", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ email }),
});
setStatus(response.ok ? "done" : "error");
} catch {
setStatus("error");
}
}
if (status === "done") {
return <p>Thanks. Check your inbox.</p>;
}
return (
<form
onSubmit={(event) => {
event.preventDefault();
send();
}}
>
<h2>{title}</h2>
<label htmlFor="email">Email</label>
<input
id="email"
type="email"
required
value={email}
onChange={(event) => setEmail(event.target.value)}
/>
<button type="submit" disabled={status === "sending"}>
{status === "sending" ? "Sending..." : buttonLabel}
</button>
{status === "error" && <p>Something went wrong. Please try again.</p>}
</form>
);
}
What does "use client" mean?
"use client";
The first line decides where the component runs. In Next.js, pages and layouts are Server Components unless you say otherwise: they run on the server and send finished HTML to the browser. "use client" turns this file, and everything it imports, into a Client Component: it's drawn once on the server for the first version of the page, then sent to the visitor's browser and runs there.
Next.js's own docs say when you need one: for "state and event handlers", such as onClick and onChange, and for browser-only things like localStorage and window. This form needs both: it remembers what's been typed, and it reacts when the form is sent. So "use client" is right here.
The thing to remember: everything in a "use client" file, and in every file it imports, can be read by anyone who visits the page. No secrets, no keys, no prices the visitor shouldn't be able to change. In a React app built with Vite there's no such line, because almost everything runs in the browser anyway.
Imports and types
import { useState } from "react";
An import brings in code from somewhere else: here, useState, from React. You'll meet it in a moment.
type Props = {
title: string;
buttonLabel?: string;
};
TypeScript is JavaScript with labels on it. This block describes what the component expects to be given: a title that's text, and a buttonLabel that's text too. The ? means it's optional. These labels don't exist when the code runs; they're there to catch mistakes, and they're a good map of what a component needs.
What are props?
export default function SignupForm({ title, buttonLabel = "Sign up" }: Props) {
Here's the component itself: a function called SignupForm. export default means other files can import it.
The part in brackets is its props, short for properties: the values the page that uses it passes in. Somewhere else in the project there'll be a line like this:
<SignupForm title="Get the newsletter" />
buttonLabel = "Sign up" gives a default, so the button says "Sign up" unless someone passes something else. To find where a component is used, search the project for <SignupForm.
What is state?
const [email, setEmail] = useState("");
const [status, setStatus] = useState("idle");
This is state. useState gives the component a value it remembers between redraws, and a function to change it. email starts empty. status starts as "idle".
The rule that makes React click: when state changes, React draws the component again. Calling setStatus("sending") changes what status is, and the whole function runs again with the new value. That's how the button can say "Sending..." a moment after it's pressed. Nothing reaches in and changes the button. The component is drawn again, and this time status is different.
The function that sends the form
async function send() {
setStatus("sending");
This runs when the form is sent (you'll see how in a moment). async means the function can wait for things, and the next lines do.
try {
const response = await fetch("/api/subscribe", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ email }),
});
setStatus(response.ok ? "done" : "error");
} catch {
setStatus("error");
}
}
fetch sends a request to an address: here, /api/subscribe, one of the app's own server routes. It sends the email address as JSON, a plain text format for data. await waits for the answer.
response.ok is true when the server answered with a status that means success. The ? : is a short way of writing if and else: if it went well, "done", otherwise "error". And if the request fails completely, say the visitor's Wi-Fi drops, the catch block sets "error" too.
That's a good sign, by the way. Lots of AI-written code has a catch that does nothing. This one tells the visitor.
The early return
if (status === "done") {
return <p>Thanks. Check your inbox.</p>;
}
Once it's sent, the component returns a thank-you message instead of the form. === means "is exactly equal to". One = sets a value. Three compare two values.
JSX: the part that looks like HTML
return (
<form
onSubmit={(event) => {
event.preventDefault();
send();
}}
>
<h2>{title}</h2>
What a component returns looks like HTML and isn't quite. It's called JSX. Three differences cover most of what you'll see:
- Curly braces mean JavaScript.
{title}puts the value oftitleon the page.onSubmit={...}tells the form what to do when it's sent. - A few attributes are renamed.
classisclassName, andforon a label ishtmlFor. - Events are props.
onChange,onClickandonSubmittake a function to run when that thing happens.
The onSubmit here is a small function written in place: (event) => { ... } is a short way to write one. When the form is sent it does two things. event.preventDefault() stops the browser doing what it would do with a form on its own, which is to load a new page. Then it calls send().
<input
id="email"
type="email"
required
value={email}
onChange={(event) => setEmail(event.target.value)}
/>
The input shows whatever's in email, and every key pressed calls setEmail with the new text. That loop, state into the input and the input back into state, is how almost every React form works.
{status === "error" && <p>Something went wrong. Please try again.</p>}
&& here means "only if". If status is "error", the message is shown. If not, nothing is.
The question to ask of every line
You've now read every line. Here's the habit that turns reading into checking: for each part, ask what does this assume?
Take type="email" and required. They make the browser check the address before the form is sent. Useful for the visitor. But they're in the browser, and anyone can skip the browser and send whatever they like straight to /api/subscribe. So the real question is: does the server route check it too? Open app/api/subscribe/route.ts and find out. The check in the browser is for the visitor's convenience. The check on the server is the one that counts.
That's what an AI misses most often. The component looks finished, and the code that has to be right is in a different file.
The same idea on the server
Here's the other kind: a Server Component, a page that runs on the server.
// app/orders/page.tsx
import { getOrders } from "@/lib/orders";
export default async function OrdersPage() {
const orders = await getOrders();
return (
<ul>
{orders.map((order) => (
<li key={order.id}>
{order.reference}: {order.total}
</li>
))}
</ul>
);
}
No "use client", so it runs on the server. It can wait for data (async and await) before the page is sent. orders.map goes through the list and makes an <li> for each order. key gives React a way to tell the items apart: a missing key is one of the warnings you'll see in lesson 7.
Now ask what it assumes. getOrders() is called with nothing. Whose orders does it get? If the answer is "everyone's", every visitor sees every customer's orders. Open lib/orders and look.
One more trap worth knowing now. A Server Component can use secret keys safely: they stay on the server, unless the code puts them on the page or passes them to a Client Component. If an AI moves code that uses a secret into a "use client" file, the secret stops working, because Next.js only lets NEXT_PUBLIC_ variables reach the browser. The "fix" an AI sometimes reaches for is to rename the key to NEXT_PUBLIC_.... Lesson 6 explains why that's worse than the error.
A good guard against it: put import "server-only"; at the top of any file that uses a secret. Next.js's docs recommend it, and it makes the build fail if browser code ever imports that file.
If you built something with AI
What to check
- For each component in your app, you know whether it runs in the browser or on the server. Search for
"use client"to find where browser code starts: those files, and every file they import, run in the browser. - No
"use client"file holds a key, a password, or a calculation the visitor mustn't be able to change, such as a price or a discount. - Every form checks its input on the server as well as in the browser. Find the route each form sends to, and look for the check.
- Every page that shows one person's data gets it for the person who's logged in, not for everyone.
If you're learning the trade
Try it
Take one component from your project, or from the Next.js app you made in lesson 2. Pick one with a form or a button in it.
- Print it out or paste it into a notes file, and write a plain-English sentence beside every line. Mark the lines you can't explain.
- Find its props: where is it used, and what's passed in?
- Find its state: what does it remember, and what changes it?
- Mark where it runs: browser or server. Then list what it assumes about the person using it.
Keep the lines you couldn't explain. In the next lesson you'll get the AI to explain them, and then check whether it's right.