Skip to content

What Runs Where

The Course
•
15 min study

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.

Browser-only values Next.js · 5 files
import "./globals.css"; export default function RootLayout({ children }) { return ( <html lang="en"> <body> <header>Study Hub</header> {children} </body> </html> ); } import ScreenSize from "./ScreenSize.jsx"; import ReadingTime from "./ReadingTime.jsx"; export default function HomePage() { const generatedAt = new Date(); return ( <main> <h1>What runs where</h1> <ScreenSize /> <ReadingTime words={1200} generatedAt={generatedAt} /> </main> ); } "use client"; export default function ReadingTime({ words, generatedAt }) { const minutes = Math.ceil(words / 200); return ( <p> About {minutes} minutes to read. The page was made at{" "} {generatedAt instanceof Date ? "a Date" : "something else"}. </p> ); } "use client"; import { useEffect, useState } from "react"; 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>; } body { font: 16px/1.5 system-ui, sans-serif; margin: 0; color: #1c2430; } header, main, footer { max-width: 36rem; margin: 0 auto; padding: 0.75rem 1rem; } header { border-bottom: 1px solid #d6dde6; } nav { display: flex; gap: 1rem; } a { color: #06617f; } h1 { margin: 0.5rem 0; } .muted { color: #5b6876; } .card { border: 1px solid #d6dde6; border-radius: 8px; padding: 0.75rem 1rem; margin-bottom: 0.75rem; }
Runs with real Next.js on your computer: unzip, then npm install and npm run dev.
Add and remove files here; write their code in the editor.

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:

JSX
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:

JSX
"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:

Text
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:

JSX
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:

JSX
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 componentClient component
Marked withnothing: the default"use client" at the top
Can be async and await datayesno
useState, effects, event handlersnoyes
Its code is sent to the browsernoyes
Renders on the serveryesyes, on real Next.js, then again in the browser
Exercise

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.

Your working space Next.js · 5 files
import "./globals.css"; export default function RootLayout({ children }) { return ( <html lang="en"> <body> <header>Study Hub</header> {children} </body> </html> ); } import ScreenSize from "./ScreenSize.jsx"; import ReadingTime from "./ReadingTime.jsx"; export default function HomePage() { const generatedAt = new Date(); return ( <main> <h1>What runs where</h1> <ScreenSize /> <ReadingTime words={1200} generatedAt={generatedAt} /> </main> ); } "use client"; export default function ReadingTime({ words, generatedAt }) { const minutes = Math.ceil(words / 200); return ( <p> About {minutes} minutes to read. The page was made at{" "} {generatedAt instanceof Date ? "a Date" : "something else"}. </p> ); } "use client"; import { useEffect, useState } from "react"; 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>; } body { font: 16px/1.5 system-ui, sans-serif; margin: 0; color: #1c2430; } header, main, footer { max-width: 36rem; margin: 0 auto; padding: 0.75rem 1rem; } header { border-bottom: 1px solid #d6dde6; } nav { display: flex; gap: 1rem; } a { color: #06617f; } h1 { margin: 0.5rem 0; } .muted { color: #5b6876; } .card { border: 1px solid #d6dde6; border-radius: 8px; padding: 0.75rem 1rem; margin-bottom: 0.75rem; }
Runs with real Next.js on your computer: unzip, then npm install and npm run dev.
Add and remove files here; write their code in the editor.
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:

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 />.

Was this article helpful?

Your response is saved on this device.