Lesson 10 +10 XP

Client Components and 'use client' Directive

Client Components and 'use client' Directive

When your user interface requires client-side interactivity, state management, or browser APIs, you declare a Client Component using the 'use client' directive.

Declaring a Client Component

Place the string 'use client'; at the very top of your component file, before any import statements:

// components/Counter.tsx
'use client';

import { useState } from 'react';

export default function Counter({ initialCount = 0 }: { initialCount?: number }) {
  const [count, setCount] = useState(initialCount);

  return (
    <div className="flex items-center gap-4">
      <button
        onClick={() => setCount((prev) => prev - 1)}
        className="px-3 py-1 bg-red-500 text-white rounded"
      >
        -
      </button>
      <span className="font-bold text-lg">{count}</span>
      <button
        onClick={() => setCount((prev) => prev + 1)}
        className="px-3 py-1 bg-green-500 text-white rounded"
      >
        +
      </button>
    </div>
  );
}

The Client Boundary Concept

The 'use client' directive defines a network boundary between Server and Client modules.

Once a file is marked with 'use client', all files imported into it automatically become part of the client bundle.

app/page.tsx (Server Component)
└── components/Header.tsx (Server Component)
    └── components/SearchInput.tsx ('use client')  <-- Boundary starts here
        ├── components/Icon.tsx                    <-- Bundled for Client
        └── utils/filter.ts                        <-- Bundled for Client

When to use Client Components

Use Client Components when you need:

  • Interactive state (useState, useReducer, useContext).
  • Lifecycle hooks (useEffect, useLayoutEffect).
  • Browser DOM event listeners (onClick, onChange, onSubmit, onKeyDown).
  • Browser web APIs (window, document, navigator.geolocation, localStorage).
  • Custom React hooks that depend on state or browser APIs.

TL;DR

  • Add 'use client'; at the top of the file to mark it as a Client Component.
  • Client Components pre-render on the server during initial page render, then hydrate on the browser.
  • All dependencies imported inside a 'use client' file are included in the client bundle.
  • Keep Client Components at the leaves of your component tree to minimize client bundle size.