読み方のヒント

矢印ボタン(または ← → キー)でページを移動できます。

第2節 "use client" でクライアント側の部品にする

2.1 "use client" を書く

QuantityPicker のファイルの先頭に、"use client" を書きます。

// src/components/QuantityPicker.tsx
"use client";

import { useState } from "react";

export const QuantityPicker = ({ max }: { max: number }) => {
  const [quantity, setQuantity] = useState(1);

  return (
    <div>
      <button type="button" onClick={() => setQuantity((q) => Math.max(q - 1, 1))}>-</button>
      <span>{quantity}個</span>
      <button type="button" onClick={() => setQuantity((q) => Math.min(q + 1, max))}>+</button>
    </div>
  );
};
// src/app/products/[id]/page.tsx(Server Component)
import { QuantityPicker } from "@/components/QuantityPicker";

export default async function ProductPage({ params }: PageProps<"/products/[id]">) {
  const { id } = await params;
  const product = await getProduct(id);
  if (product === undefined) notFound();

  return (
    <main>
      <h1>{product.name}</h1>
      <p>{product.price}円</p>
      {product.reservable && <QuantityPicker max={10} />}
    </main>
  );
}

"use client" は、「このファイルから先は、ブラウザでも動く」という境目の印です。Client Components も、最初はサーバーで HTML になって届き、そのあとブラウザで JavaScript が動いて、ボタンが押せるようになります。

比べる点Server ComponentsClient Components
書き方何も書かないファイルの先頭に "use client"
動く場所サーバーだけサーバー(最初の HTML)とブラウザ
state・イベント使えない使える
データを直接読むできるできない
ブラウザに送る JavaScript増えない部品の分だけ増える

6 / 16