There's one more twist. On a real Next.js site, client components render on the server too, once, to produce the first HTML, so the page appears before any JavaScript arrives. Then they render again in the browser and become interactive.
So a client component's render must work in both places. Effects and event handlers only ever run in the browser.
npm install and npm run dev. Browser values belong in effects
window, document, navigator and localStorage only exist in the browser.
ScreenSize reads the window's width in an effect, so the server's render
shows …, and the browser fills in the number:
export default function ScreenSize() {
// window only exists in the browser, so read it in an effect.
const [width, setWidth] = useState(null);
useEffect(() => {
setWidth(window.innerWidth);
}, []);
return <p>Window width: {width === null ? "…" : `${width} px`}</p>;
}The labs are more forgiving
These labs don't render client components on the server, so reading window
directly during render seems to work here. On real Next.js it doesn't:
next build stops with ReferenceError: window is not defined, and next dev
answers with an error. Always read browser values in an effect or an event
handler.
The two renders must match
Rendering twice brings a second rule. The browser's first render doesn't build a new page: it hydrates the HTML the server sent, attaching event handlers to the elements that are already there. For that, React expects the browser's first render to produce exactly the same output as the server's.
Anything that gives a different answer each time it runs breaks that:
"use client";
export default function Greeting() {
// Wrong: the server and the browser each pick their own number.
return <p>Lucky number: {Math.floor(Math.random() * 100)}</p>;
}Trace it on real Next.js. The server renders Lucky number: 42 into the HTML.
The browser renders again and gets Lucky number: 7. React finds text that
doesn't match what's on the page, and in next dev reports:
Hydration failed because the server rendered text didn't match the client.It then throws away the server's HTML for that part and builds it again in the
browser, so the quick first view was wasted. The message goes on to list the
usual causes: Date.now(), Math.random(), a branch on
typeof window !== "undefined", and dates formatted in the reader's own locale
(toLocaleString), which the server doesn't know.
The fix is the one you just saw. Render something both sides agree on, then change it in an effect, which only runs in the browser after hydration:
const [lucky, setLucky] = useState(null);
useEffect(() => {
setLucky(Math.floor(Math.random() * 100));
}, []);
return <p>Lucky number: {lucky ?? "…"}</p>;That's why ScreenSize starts at …: the server can't know the width, so
both renders show … first.
Only real Next.js shows this
The labs render client components only in the browser, so there's nothing to
compare and you'll never see this error here. Look for it the first time you
run a project with next dev (Day 7).
Predict
ReadingTime receives generatedAt, a Date made on the server. Suppose it
showed the time with generatedAt.toLocaleTimeString() during render. On real
Next.js, a reader in Tokyo opens a page rendered by a server in London. Do the
two renders match?
Check your prediction
No. The Date is the same moment on both sides, but toLocaleTimeString()
formats it in the time zone and language of the place that runs it: London on
the server, Tokyo in the browser. The text differs, so hydration fails. Format
it in an effect, or on the server and pass the finished string.
Only data crosses
The page passes ReadingTime a number and a Date, and both arrive intact.
Next.js can send data: strings, numbers, booleans, arrays, plain objects,
Date, Map and Set. Ordinary functions aren't serializable across this
boundary. Server Functions marked with "use server" are a special supported
reference: Day 5 uses them for form actions. Try passing
onDone={() => console.log("done")} to ReadingTime:
export default function HomePage() {
const generatedAt = new Date();
return (
<main>
<h1>What runs where</h1>
<ScreenSize />
<ReadingTime words={1200} generatedAt={generatedAt} />
</main>
);
}What happens
Event handlers cannot be passed to Client Component props, the same error as the last lesson. An ordinary function can't cross this boundary, even if its prop has another name. This is different from a Server Function reference, which Next.js can send as a callable action. Undo the change.
Summary
| Server component | Client component | |
|---|---|---|
| Marked with | nothing: the default | "use client" at the top |
Can be async and await data | yes | no |
useState, effects, event handlers | no | yes |
| Its code is sent to the browser | no | yes |
| Renders on the server | yes | yes, on real Next.js, then again in the browser |
The reader's language
Add a client component, Language, that shows Your browser's language:
en-US (or whatever the reader's is), from navigator.language. Show …
until it's known.
npm install and npm run dev. Hint 1: the idea
The initial render must work without browser APIs. Fill in browser-specific information after the component mounts.
Hint 2: a first step
Copy the shape of ScreenSize: state that starts as null, set in an effect.
Show one solution
app/Language.jsx:
"use client";
import { useEffect, useState } from "react";
export default function Language() {
const [language, setLanguage] = useState(null);
useEffect(() => {
setLanguage(navigator.language);
}, []);
return <p>Your browser's language: {language ?? "…"}</p>;
}Import it in app/page.jsx, and render <Language /> under <ScreenSize />.
Completion is saved in this browser only. It does not measure mastery.