AgendaViva already has several Client Components: the active link, the modal, the error notices. You wrote them by copying 'use client' into the first line. The directive's name is misleading, because it doesn't mean "run only on the client", and that confusion is behind almost every hydration error.

In this lesson you'll see what the directive declares and how far it reaches, what steps a Client Component goes through from the HTML to responding to a click, why hydration fails and how to handle data that only the browser knows. You'll apply it to the guide's favorites, stored in localStorage, and finish with the technique that saves the most JavaScript: keeping the interactive parts small.

  1. What the directive declares

'use client' applies to a module, not to a component. It says: "what this file exports is an entry point to the client". When a Server Component imports it, the bundler doesn't include its code on the server side of the tree; it puts a reference there, the same one you saw in the RSC Payload.

The rules for writing it are few:

  • It goes on the first line, before the import statements. Only comments can come before it.
  • With single or double quotes, never with backticks.
  • It can't go inside a function. A file is a client file as a whole.

1.1. The directive spreads downward

Everything that module imports becomes part of the client graph, even without the directive. NavLink imports Link; if it imported lib/format.ts, that would travel too.

flowchart TD
    subgraph Server
      P["header.tsx"]
      T["event-card.tsx"]
      F["lib/format.ts"]
    end
    subgraph Client["Client graph"]
      E["nav-link.tsx<br/>'use client'"]
      L["next/link"]
      B["favorite-button.tsx<br/>'use client'"]
      V["lib/favorites.ts"]
    end
    P --> E
    E --> L
    T --> F
    T --> B
    B --> V

Three things follow from this:

  • Marking the boundary is enough. A component used only by other client components doesn't need the directive. Adding it does nothing: "between client and client" there's no boundary to cross.
  • The same module can be on both sides. lib/format.ts has no directive. Imported from EventCard, it runs on the server; imported from a Client Component, it's compiled again for the browser. The same goes for a component without the directive: server or client isn't a property of the file, but of each use.
  • There's no server directive for components. 'use server' exists, but it declares Server Actions (06-01), not Server Components. Those are the default case.

1.2. When you need it

You need… Client Component?
useState, useReducer, useEffect, useRef Yes
onClick, onChange or another handler Yes
window, localStorage, navigator, observers Yes
A hook that uses any of the above (usePathname, useRouter…) Yes
React context Yes
To render a Client Component inside it No: a Server Component can render it
A form that navigates or calls a Server Action Not necessarily
Styles, CSS animations, <details> No

  1. The lifecycle of a Client Component

On a full load, a Client Component goes through four stages:

Stage Where What happens Effects and events
1. Prerendering Server The function runs to generate HTML No
2. First paint Browser The HTML is visible; nothing responds yet No
3. Hydration Browser It runs again and is wired up to that HTML They're registered
4. Normal life Browser It updates with its state Yes

On a client-side navigation only the fourth exists: the function runs in the browser for the first time and there's no prior HTML to compare against. That's why a hydration error may not show up when you navigate and appear when you reload. When you review a Client Component, always test both ways of arriving.

Hydration has one requirement: the run in stage 3 must produce exactly the same thing as stage 1. React doesn't repaint; it trusts that the HTML is what it would have generated itself.

  1. Hydration errors

If they don't match, React warns you. The message, abridged, is this:

Hydration failed because the server rendered text didn't match the
client. As a result this tree will be regenerated on the client.
This can happen if a SSR-ed Client Component used:
- A server/client branch `if (typeof window !== 'undefined')`.
- Variable input such as `Date.now()` or `Math.random()`
- Date formatting in a user's locale which doesn't match the server.
- External changing data without sending a snapshot of it
- Invalid HTML tag nesting.

The consequence isn't just the warning. React discards the HTML up to the nearest Suspense or error boundary and generates it again in the browser: the content flickers and the server's work is lost.

Cause Example Fix
A date in the local settings date.toLocaleString() A format with an explicit locale and time zone, like formatDateTime
Clock or randomness during render Date.now(), Math.random() A value calculated on the server and passed as a prop, or in an event
Made-up identifiers id={Math.random()} useId
Reading the browser during render localStorage.getItem(…) Sections 4 and 5
Branches on typeof window window ? <A /> : <B /> Same
Invalid HTML A <div> inside a <p>, an <a> inside an <a> Fix the markup
Browser extensions Added attributes Not yours; check in a window without extensions

With Cache Components, some of these cases fail earlier. A Client Component that calls Date.now() during render, with no <Suspense> above it, produces a prerendering error: Next.js can't freeze "now" into the shell.

There's an escape hatch, suppressHydrationWarning, which silences the mismatch for one element, without reaching its children; React then keeps what's in the DOM. It's legitimate when the difference is unavoidable and intended, like the color theme in 03-04. To cover up an error you don't understand, it isn't.

  1. Favorites: data that lives in the browser

Visitors will be able to mark events as favorites without an account. The list is stored in localStorage, so the server doesn't know it. It's the most common case of conflict with hydration. This version, which looks correct, fails:

// Wrong: reads the browser on the first render
const [isFavorite, setIsFavorite] = useState(
  () => localStorage.getItem('agendaviva:favorites')?.includes(eventId) ?? false,
)

On the server there's no visitor localStorage: depending on the Node version, the name doesn't exist and throws an error, or it exists and is empty. Guarding it with typeof window === 'undefined' avoids the error, but moves the problem: the server renders "no" and hydration, "yes".

React has a tool for reading external sources that change, useSyncExternalStore. It takes three functions: how to subscribe to changes, how to read the value and which value to use on the server and during hydration.

// lib/favorites.ts
import { useSyncExternalStore } from 'react'

const KEY = 'agendaviva:favorites'
const listeners = new Set<() => void>()

function subscribe(onChange: () => void): () => void {
  listeners.add(onChange)
  window.addEventListener('storage', onChange)
  return () => {
    listeners.delete(onChange)
    window.removeEventListener('storage', onChange)
  }
}

function read(): string {
  try {
    return localStorage.getItem(KEY) ?? '[]'
  } catch {
    return '[]' // Storage blocked by the browser
  }
}

function readOnServer(): string {
  return '[]'
}

function parse(text: string): string[] {
  try {
    const value: unknown = JSON.parse(text)
    if (!Array.isArray(value)) return []
    return value.filter((id): id is string => typeof id === 'string')
  } catch {
    return []
  }
}

export function toggleFavorite(eventId: string): void {
  const ids = parse(read())
  const next = ids.includes(eventId)
    ? ids.filter((id) => id !== eventId)
    : [...ids, eventId]

  try {
    localStorage.setItem(KEY, JSON.stringify(next))
  } catch {
    return
  }
  listeners.forEach((notify) => notify())
}

export function useFavorites(): string[] {
  const text = useSyncExternalStore(subscribe, read, readOnServer)
  return parse(text)
}
  • readOnServer returns an empty list. It's used when prerendering and also during hydration, so the two match. Immediately afterwards, React compares with read() and, if it differs, updates. There's no error, just a second render.
  • The value read is the text, not the array. React compares with Object.is: if read returned JSON.parse(…), each call would produce a different array and the component would update endlessly. The text is a primitive value and compares cleanly; it's parsed afterwards.
  • Two notification paths. The storage event is only fired in the other tabs. For components on the same page there's listeners.
  • parse is suspicious. Anyone can edit what's stored, or it may come from an earlier version of the application.
  • There's no directive. Only Client Components import the module. In 03-05 you'll add a safeguard so that it stays that way.
// components/favorite-button.tsx
'use client'

import { toggleFavorite, useFavorites } from '@/lib/favorites'

interface Props {
  eventId: string
  title: string
}

export function FavoriteButton({ eventId, title }: Props) {
  const isFavorite = useFavorites().includes(eventId)

  return (
    <button
      type="button"
      aria-pressed={isFavorite}
      aria-label={`Favorite: ${title}`}
      onClick={() => toggleFavorite(eventId)}
      className="text-xl leading-none"
    >
      {isFavorite ? '★' : '☆'}
    </button>
  )
}

It receives two strings and not the whole event: that's all it needs. Place it in the card, next to the title, and in the heading of EventDetails in the same way:

// components/event-card.tsx (the title; imports FavoriteButton)
<div className="flex items-start justify-between gap-2">
  <h3 className="text-lg font-semibold">
    <Link href={`/events/${event.slug}`}>{event.title}</Link>
  </h3>
  <FavoriteButton eventId={event.id} title={event.title} />
</div>

EventCard is still a server component. Only the button crosses over, and the six instances in the list share a single JavaScript file. Mark a favorite, open the same page in another tab and watch them stay in sync.

  1. When there's nothing useful to render on the server

The empty star is a reasonable fallback while you don't know. In a counter, on the other hand, "0 favorites" would be false information. For that case, React 19.3 offers browser, from react-dom: when you call use(browser()), the component suspends on the server, and the fallback of the nearest <Suspense> is left in its place. In the browser it does nothing and the component renders normally.

// components/favorites-counter.tsx
'use client'

import { use } from 'react'
import { browser } from 'react-dom'
import { useFavorites } from '@/lib/favorites'

export function FavoritesCounter() {
  use(browser('Favorites are stored in localStorage.'))
  const total = useFavorites().length
  if (total === 0) return null

  return (
    <span>
      ★ {total} <span className="sr-only">favorites</span>
    </span>
  )
}
// components/header.tsx (at the end of the <nav>)
<Suspense fallback={null}>
  <FavoritesCounter />
</Suspense>

The <Suspense> is required; without it, rendering on the server fails. And whatever ends up inside it won't be in the initial HTML: don't use it for content that search engines need to read.

This used to be done with a mounted state that an effect set to true, or with next/dynamic and ssr: false. You'll find the first in a lot of code; it causes an extra render and the React linter usually advises against it. The second is still useful when a library accesses window when it's imported, because then suspending the component isn't enough (10-02).

5.1. Where to touch the browser

Place Does it run on the server? Use it for
Module body Yes Constants; never window
Component body Yes Pure calculations
useSyncExternalStore Only its third function Reading something external that changes
useEffect, useLayoutEffect No Subscribing, measuring, focusing, integrating libraries
Event handlers No Responding to an action

Handlers are the safest place and the most underused. To know which address the visitor is on when they click "Share" you don't need any hook: window.location is read in the click.

One subtlety of effects with Cache Components: when the page is hidden on navigation, its effects are cleaned up, and they run again if it reappears. Always return the cleanup function, as the 02-05 modal did when closing the dialog.

5.2. Route parameters: useParams

A Client Component doesn't receive params, but it can read the dynamic segments with useParams, from next/navigation. It returns an object, not a promise:

'use client'

import { useParams } from 'next/navigation'

export function EventBreadcrumb() {
  const { slug } = useParams<{ slug: string }>()
  return <span>events / {slug}</span>
}

The same thing happens to it as to usePathname: in /events/[slug] the value isn't known at build time, so the hook suspends and needs a <Suspense>. The type parameter is your own assertion; nobody checks that the segment exists. If a nearby Server Component already has the slug, passing it as a prop is simpler and clearer. Save the hook for deeply nested components or ones shared between routes.

  1. Small islands

Suppose that, to add the favorite to the event page, someone writes 'use client' in event-details.tsx. The consequences:

  • EventLocation is async and stops working, because it's now part of the client.
  • lib/data/venues.ts and the in-memory data end up in the browser's JavaScript.
  • The whole event travels as a prop, with all its fields.
  • The entire event page is hydrated for the sake of one button.

The technique is always the same: push the directive down to the leaf that needs it.

Sign What to do
The page has 'use client' because of a button Extract the button
A layout is a client component because of the dropdown menu Extract the menu; the layout passes the rest as children
A card is a client component because of a decorative onMouseEnter Use CSS (:hover, group-hover)
A list is a client component to highlight the active item Only the item that reads the route, like NavLink
A form is a client component because of a character counter Only the field with its counter

Don't take it to the extreme either. If an area is mostly interactive, like an editor or a calendar, a single well-scoped Client Component is more readable than ten islands talking to each other. The goal isn't to minimize the number of directives, but to avoid shipping what doesn't interact.

Common Mistakes and Tips

  • Believing 'use client' avoids the server. The component is prerendered. If it really mustn't run there, use(browser()).
  • Putting the directive in every file of a client subtree. It's only needed at the entry point, and in the others it hides where the boundary is.
  • Returning a new object from getSnapshot. React warns you and can get stuck in a loop. Return a primitive or a stored value.
  • Only testing by navigating. Hydration errors show up when you reload.
  • Using suppressHydrationWarning as a general remedy. It hides the symptom, and React doesn't fix the content.
  • Formatting dates on the client without a time zone. It's the most common hydration error, and you won't see it on your machine if its zone matches the server's.
  • Storing in state what can be calculated. isFavorite is derived from the list; copying it into a useState forces you to keep it in sync.

Exercises

Exercise 1: sharing an event

Create components/share-button.tsx with a title prop. When clicked, it uses navigator.share if it exists and, if not, copies the address and shows "Link copied". Canceling the system dialog isn't an error. Place it in EventDetails.

Solution

// components/share-button.tsx
'use client'

import { useState } from 'react'

export function ShareButton({ title }: { title: string }) {
  const [message, setMessage] = useState('')

  async function handleShare() {
    const url = window.location.href
    try {
      if (typeof navigator.share === 'function') {
        await navigator.share({ title, url })
      } else {
        await navigator.clipboard.writeText(url)
        setMessage('Link copied')
      }
    } catch (error) {
      if (error instanceof DOMException && error.name === 'AbortError') return
      setMessage("Couldn't share")
    }
  }

  return (
    <p className="mt-4">
      <button type="button" onClick={handleShare} className="underline">
        Share
      </button>{' '}
      <span role="status">{message}</span>
    </p>
  )
}

Everything browser-related is in the handler, so the render is identical on both sides and there's no hydration risk. The navigator.share check is also done in the click: if it decided the button's text during render, the server and the browser might not match. The role="status" announces the message to screen readers. The course keeps this component in EventDetails.

Exercise 2: a spots selector

Write a SpotsSelector Client Component that receives max and shows a minus button, the number and a plus button, between 1 and max. The value must be submittable in a form under the name spots. Which part would be unnecessary if a number field were enough?

Solution

'use client'

import { useState } from 'react'

export function SpotsSelector({ max }: { max: number }) {
  const [spots, setSpots] = useState(1)

  return (
    <div className="flex items-center gap-3">
      <button
        type="button"
        aria-label="Remove a spot"
        disabled={spots <= 1}
        onClick={() => setSpots((current) => Math.max(1, current - 1))}
      >
        −
      </button>
      <output aria-live="polite">{spots}</output>
      <button
        type="button"
        aria-label="Add a spot"
        disabled={spots >= max}
        onClick={() => setSpots((current) => Math.min(max, current + 1))}
      >
        +
      </button>
      <input type="hidden" name="spots" value={spots} />
    </div>
  )
}

With <input type="number" name="spots" min={1} max={max} defaultValue={1} /> the whole component would be unnecessary: the browser provides the buttons, the limits and the submission, without hydrating anything. The client version is only justified if the design demands it. It's a practice exercise; the booking form arrives in module 6, and there the limit will also be checked on the server.

Exercise 3: diagnosing hydration

This component fails in production with a hydration error and, on some routes, at build time. Find the three causes and fix them.

'use client'

export function EventNotice({ startsAt }: { startsAt: Date }) {
  const days = Math.ceil((startsAt.getTime() - Date.now()) / 86_400_000)
  const isMobile = typeof window !== 'undefined' && window.innerWidth < 640

  return (
    <p>
      {isMobile ? 'In' : 'The event starts in'} {days} days, on{' '}
      {startsAt.toLocaleDateString()}
    </p>
  )
}

Solution

  1. Date.now() during render. The server and the browser calculate at different moments and, if it ends up in the shell, Next.js fails at build time.
  2. typeof window. It makes the two sides render different text. Width is a job for CSS.
  3. toLocaleDateString() without settings. It depends on each machine's locale and time zone.

It doesn't need to be a client component: the server can calculate the days, after io() and inside a <Suspense>.

import { io } from 'next/cache'
import { formatDateTime } from '@/lib/format'

export async function EventNotice({ startsAt }: { startsAt: Date }) {
  await io()
  const days = Math.ceil((startsAt.getTime() - Date.now()) / 86_400_000)

  return (
    <p>
      <span className="hidden sm:inline">The event starts in</span>
      <span className="sm:hidden">In</span> {days} days, on{' '}
      {formatDateTime(startsAt)}
    </p>
  )
}

io(), which you know from 01-04, defers the calculation to request time, and each text variant exists in the HTML even though only one is visible. Whoever uses it must wrap it in a <Suspense>.

Conclusion

'use client' marks a module as an entry point to the client and drags along everything it imports. It doesn't avoid the server: the component is prerendered and then hydrated, and both runs must match. For what only the browser knows you have useSyncExternalStore, with an explicit server value, and use(browser()), when there's nothing honest to render; for everything else, event handlers. And the lower the directive, the better.

Favorites have crossed the boundary with two strings. But dates, server children and promises cross it too, while an arbitrary function can't. What gets through, what doesn't and how to compose the two worlds is the subject of The Server-Client Boundary: Serialization and Composition.

© Copyright 2026. All rights reserved