Menu

Client Components

Lesson 2: Client Components

What is a Client Component?

A Client Component is a component that also runs in the browser, so it can respond to clicks, keep state, and use browser APIs. You create one by adding 'use client' at the top of its file.

Client Components are still rendered to HTML on the server for the first load, then hydrated in the browser to become interactive.

When to choose which

You need to… Use
Fetch data, access a database, use secrets Server Component
Render static content, large libraries, Markdown Server Component
Handle clicks, typing, or form input state Client Component
Use useState, useEffect, useReducer, or context Client Component
Use window, localStorage, geolocation Client Component
Use a library built on hooks, such as a chart or carousel Client Component

Example

// app/courses/[slug]/EnrolButton.tsx
'use client';

import { useState } from 'react';

export function EnrolButton({ courseTitle }: { courseTitle: string }) {
  const [saved, setSaved] = useState(false);

  return (
    <button onClick={() => setSaved(!saved)}>
      {saved ? `Saved ${courseTitle} ✓` : 'Save for later'}
    </button>
  );
}
// app/courses/[slug]/page.tsx (Server Component)
import { EnrolButton } from './EnrolButton';

export default async function CoursePage({ params }: PageProps<'/courses/[slug]'>) {
  const { slug } = await params;
  const course = await getCourse(slug);
  return (
    <article>
      <h1>{course.title}</h1>
      <EnrolButton courseTitle={course.title} />
    </article>
  );
}

How it works

  • 'use client' marks a boundary. That file and every component it imports become part of the browser bundle.
  • You only need the directive at the entry point, not in every child file.
  • The page stays a Server Component; only the button is sent as JavaScript.

Common mistakes

Mistake Effect Fix
'use client' on the page or root layout Whole tree ships to the browser Push the directive down to the smallest interactive part
Reading window during render "window is not defined" on the server Read it inside useEffect or an event handler
Rendering Date.now() or random values Hydration mismatch warning Compute them in an effect or pass them from the server
Directive below imports Directive ignored 'use client' must be the first line

Key takeaways

  • Use Client Components only for interactivity and browser APIs.
  • Keep them small and place them as low in the tree as possible.

Try it: Build a SearchBox Client Component that filters a list of course titles as the user types.


Nextjs Tutorial

J

Jebasta





Get in Touch For Details