Client Components

The 'use client' Directive

Write 'use client' at the very top of a file to make it a Client Component. It is still rendered to HTML on the server first, then hydrated in the browser so it becomes interactive.

components/AddToCartButton.tsx

'use client';

import { useState } from 'react';

export default function AddToCartButton({ productId }: { productId: number }) {
  const [qty, setQty] = useState(0);

  return (
    <div>
      <button onClick={() => setQty(qty + 1)}>Add to Cart</button>
      {qty > 0 && <span>{qty} in cart (product {productId})</span>}
    </div>
  );
}

The Boundary

'use client' marks a boundary. The file and every component it imports become part of the client bundle. So put the directive on small leaf components, not on whole pages.

ProductPage (server)            <- fetches product, 0 KB JS
├── ProductGallery (server)
├── ProductDetails (server)
└── AddToCartButton ('use client')  <- only this ships JS
    └── QuantityPicker            <- imported by a client file: client too