Logicoya
HOME › オンライン教材 › Next.js で作る予約システム › Lesson 9 Client Component と状態管理
9

Client Component と状態管理

use client

use client とは

ここから作る BookingContext.tsx と BookingForm.tsx は、ファイルの先頭に "use client" を書きます。Server Component と Client Component の違いを、予約ページを例にもう一度整理します。

Next.js のデフォルトは Server Component

app/ の中のコンポーネントは、何も書かなければ Server Component になります。ファイルの先頭に "use client" を書くと、そのファイルは Client Component になります。

Server ComponentClient Component
書き方何も書かない(デフォルト)ファイルの先頭に "use client"
実行される場所サーバーのみサーバー(最初の HTML 生成)+ ブラウザ
async / await でのデータ取得できるコンポーネント自体を async にできない
フック(useState ・useContext など)使えない使える
イベント使えない使える
ブラウザに送られる JavaScript増えないコンポーネントのコード分だけ増える

よくある誤解: "use client" を付けても、「ブラウザだけで動く」わけではありません。最初の HTML はサーバー側で作られ、ブラウザに届いたあとでイベントに反応されます(ハイドレーション)。

"use client" が必要になる場面

次のどれかを使うときに必要です。

使うもの例
state やフックuseState ・ useReducer ・ useContext ・ useEffect
イベントハンドラonClick ・ onChange
ブラウザだけにある機能window ・ localStorage など
Context の ProvidercreateContext で作った Context を配る

これらを使わないコンポーネントは、Server Component のままにしておきます。

予約ページでの使い分け

ファイル種類理由
app/shop/[id]/book/page.tsxServer Componentawait getShop(id) でデータを取得
contexts/BookingContext.tsxClient ComponentcreateContext ・ useReducer ・ useContext を使う
components/booking/BookingForm.tsxClient ComponentuseBooking() で、ボタンクリックで dispatch する

page.tsx でデータを取得し、画面を操作する部分だけを BookingForm に切り出しています。こうすることで、ブラウザに送る JavaScript を必要な部分だけに抑えられます。

"use client" は境界線

"use client" は「ここから下は Client Component」という 境界線 です。境界の内側で import されたコンポーネントは、"use client" を書いていなくても Client Component として動きます。

このあと作る MenuStep などに "use client" を書かないのは、このためです。境界線は、フックやイベントを使うコンポーネントのうち、一番上のファイル に 1 回書けば十分です。

Server から Client に渡せる Props

page.tsx(Server)から BookingForm(Client)に Props を渡すとき、渡せる値には制限があります。サーバーからブラウザへ データとして送れる値 だけが渡せます。

渡せる渡せない
文字列・数値・真偽値・null関数(onClick={() => ...} など)
配列・プレーンなオブジェクト(shop ・ menus ・ staffs)クラスのインスタンス
Server Component を children として渡す

shop ・ menus ・ staffs は、API から取得した JSON をそのまま型付けしたプレーンなオブジェクトなので、そのまま渡せます。

なぜ全部 Client Component にしないのか

すべてのファイルに "use client" を書いても、多くの画面は動きます。それでも Server Component を基本にするのは、次の理由からです。

理由内容
表示が速いブラウザに送る JavaScript が少なくなり、読み込みが速くなる
安全lib/services/shops.ts のようなサーバー専用の処理(import "server-only")や、秘密の設定値をブラウザに送らずに済む
データ取得が簡単async / await でそのままデータを取得でき、useEffect などを使わなくて済む

予約フロー

「戻る」「次へ」ボタンで 4 つのステップを切り替えます。

ステップ内容
1メニューを選ぶ
2日付・時間を選ぶ
3スタッフを選ぶ(任意)
4備考を入力して確定する

ファイル一覧

パス役割種別新規 / 編集
app/shop/[id]/book/page.tsx予約ページServer Component新規
contexts/BookingContext.tsx予約フローの状態管理useReducer + Context新規
components/booking/BookingForm.tsxステップ式の入力フォームClient Component新規

予約ページ

app/shop/[id]/book/page.tsx を作成します。

店舗の情報は、画面の操作で変化しないデータなので Server Component で取得します。getShop() は、店舗詳細ページで作った関数をそのまま使います。

import { notFound } from "next/navigation"

import SectionHeading from "@/components/SectionHeading"
import { getShop } from "@/lib/services/shops"

type Props = {
  params: Promise<{ id: string }>
}

export default async function BookingPage({ params }: Props) {
  const { id } = await params

  const shop = await getShop(id)
  if (!shop) {
    notFound()
  }

  return (
    <div>
      <SectionHeading
        eyebrow="Booking"
        title={`${shop.name} の予約`}
        description="メニュー・スタッフ・日時を選んで予約します。"
      />
    </div>
  )
}

動作確認

/shop/1 の「この店舗で予約する」から、/shop/1/book にエラーなく遷移できることを確認します。


予約フローの状態管理

useReducer とは

useReducer は「どんな更新をしたいか」を表す action を送り、reducer という関数で次の状態(state)を計算する React Hooks の1つです。

要素役割
state今の状態。ここでは { step, menuId, staffId, date, time, notes }
dispatchaction を送るための関数。dispatch({ type: "next" }) のように呼ぶ
reducer受け取った action から次の state を計算して返す関数

useState との比較

予約フォームで管理する値は 6 つ(step ・ menuId ・ staffId ・ date ・ time ・ notes)あります。useState を 6 個並べると、どこでどの値を更新しているのかが追いにくくなります。useReducer なら、更新のルールを reducer 関数 1 か所にまとめられます。

useStateuseReducer
向いている場面独立した値が少ない関連する値が多い・更新パターンが複雑
更新の書き方setValue() で直接更新dispatch(action) を送り、reducer が計算
更新ロジックの場所呼び出し側に散らばるreducer 関数にまとまる

Context とは

Context は、コンポーネントの親子関係をまたいで値を共有する React の仕組みです。Provider で囲んだ範囲の中なら、どのコンポーネントからでも useContext() で値を取り出せます。

この章では、useReducer で作った state と dispatch を Context に入れて、BookingForm から取り出して使います。

要素役割
createContextContext(値の入れ物)を作る
Provider囲んだ範囲に値を配る
useContextProvider から配られた値を取り出す

BookingForm.tsx の中に useReducer を直接書くこともできますが、状態管理を別ファイルに分けておくと次の利点があります。

利点内容
役割の分離BookingForm は「画面の表示」、BookingContext は「状態の計算」に専念できる
共有しやすい将来、サマリーや各ステップから直接 useBooking() で状態を読めるようになる
読みやすい型・初期値・reducer が 1 ファイルにまとまり、更新ルールを一覧できる

BookingContext の作成

contexts/BookingContext.tsx を作成します。

状態管理の流れ

BookingContext で作る仕組みの全体像です。①〜③ の順に、画面の操作から表示の更新までがつながります。

順番動き
①BookingFlow のボタンが押され、dispatch({ type: "next" }) のように action を送る
②bookingReducer が、今の state と action から 新しい state を計算して返す
③BookingProvider が新しい state を Context で配り、useBooking() を使っている BookingFlow が再描画される

1. ステップ数

ステップの総数を定数にしておきます。4 を何か所にも直接書くと、ステップを増やしたときに直し漏れが起きるためです。

"use client"

import { createContext, useContext, useReducer } from "react"

export const TOTAL_STEPS = 4

2. BookingState

予約の状態 BookingState の型と初期値を定義します。

プロパティ型初期値内容
stepnumber1現在のステップ
menuIdstring | nullnull選択したメニューの ID
staffIdstring | nullnull選択したスタッフの ID(null は指名なし)
datestring | nullnull選択した予約日(YYYY-MM-DD)
timestring | nullnull選択した予約時間(HH:MM)
notesstring""備考
// contexts/BookingContext.tsx
export type BookingState = {
  step: number
  menuId: string | null
  staffId: string | null
  date: string | null
  time: string | null
  notes: string
}

const INITIAL_STATE: BookingState = {
  step: 1,
  menuId: null,
  staffId: null,
  date: null,
  time: null,
  notes: "",
}

3. BookingAction

dispatch で送る action の型 BookingAction を定義します。

type受け取る値内容
select-menumenuId: stringメニューを選択する
select-staffstaffId: string | nullスタッフを選択する
select-datedate: string予約日を選択する
select-timetime: string予約時間を選択する
change-notesnotes: string備考を変更する
nextなし次のステップへ進む
prevなし前のステップへ戻る
// contexts/BookingContext.tsx
export type BookingAction =
  | { type: "select-menu"; menuId: string }
  | { type: "select-staff"; staffId: string | null }
  | { type: "select-date"; date: string }
  | { type: "select-time"; time: string }
  | { type: "change-notes"; notes: string }
  | { type: "next" }
  | { type: "prev" }

| でつないだ型を ユニオン型 と呼びます。type の値ごとに、一緒に送る値が決まっています。たとえば { type: "select-menu" } だけを送ると、menuId がないため型エラーになります。

4. canGoNext

「次へ」を押せるかどうかを判定する関数 canGoNext を作ります。条件は、このあと画面を作るときに追加します。今は、ステップが範囲内であれば常に true を返します。

// contexts/BookingContext.tsx

// 「次へ」を押せるか(条件は、あとで追加する)
export function canGoNext(state: BookingState): boolean {
  return state.step <= TOTAL_STEPS
}
部分説明
export functionBookingForm からも使えるように export する
state.step <= TOTAL_STEPS今は、ステップが範囲内なら常に true。あとで、ステップごとの必須項目のチェックに置き換える

判定を canGoNext 1 か所にまとめておくと、次の「reducer」と、画面のボタンの両方で同じ判定を使えます。

5. reducer 関数

bookingReducer は、今の state と action を受け取り、次の state を返します。

// contexts/BookingContext.tsx
function bookingReducer(state: BookingState, action: BookingAction): BookingState {
  switch (action.type) {
    case "select-menu":
      return { ...state, menuId: action.menuId }
    case "select-staff":
      return { ...state, staffId: action.staffId }
    case "select-date":
      return { ...state, date: action.date }
    case "select-time":
      return { ...state, time: action.time }
    case "change-notes":
      return { ...state, notes: action.notes }
    case "next":
      if (!canGoNext(state)) return state
      return { ...state, step: Math.min(state.step + 1, TOTAL_STEPS) }
    case "prev":
      return { ...state, step: Math.max(state.step - 1, 1) }
  }
}
部分説明
{ ...state, menuId: action.menuId }元の state をコピーし、menuId だけを上書きした 新しいオブジェクト を返す
if (!canGoNext(state)) return state進めない状態のときは、state を変えずにそのまま返す
Math.min(state.step + 1, TOTAL_STEPS)step が 4 を超えないようにする
Math.max(state.step - 1, 1)step が 1 より小さくならないようにする

reducer の中で state.menuId = ... のように state を書き換えてはいけません。React では書き換えただけでは画面更新されません。

6. Provider

useReducer で作った state と dispatch を、Context に入れて配ります。shopId もここで一緒に配っておきます。

// contexts/BookingContext.tsx
type BookingContextValue = {
  shopId: string
  state: BookingState
  dispatch: React.Dispatch<BookingAction>
}

const BookingContext = createContext<BookingContextValue | null>(null)

export function BookingProvider({ shopId, children }: { shopId: string; children: React.ReactNode }) {
  const [state, dispatch] = useReducer(bookingReducer, INITIAL_STATE)

  return <BookingContext.Provider value={{ shopId, state, dispatch }}>{children}</BookingContext.Provider>
}

7. useBooking

Context を取り出すためのカスタムフック useBooking() を作ります。

// contexts/BookingContext.tsx
export function useBooking(): BookingContextValue {
  const context = useContext(BookingContext)
  if (!context) {
    throw new Error("useBooking は BookingProvider の内側で使ってください")
  }
  return context
}

createContext() の初期値を null にしているため、Provider の外で useContext() を呼ぶと null が返ります。useBooking() の中で null のときにエラーを投げておくと、次の 2 つのメリットがあります。

メリット内容
間違いに早く気づけるProvider で囲み忘れたとき、原因がはっきりしたエラーメッセージが出る
型が絞り込まれる戻り値が BookingContextValue(null なし)になり、使う側で null チェックが不要になる

完成形

// contexts/BookingContext.tsx
"use client"

import { createContext, useContext, useReducer } from "react"

export const TOTAL_STEPS = 4

export type BookingState = {
  step: number
  menuId: string | null
  staffId: string | null
  date: string | null
  time: string | null
  notes: string
}

export type BookingAction =
  | { type: "select-menu"; menuId: string }
  | { type: "select-staff"; staffId: string | null }
  | { type: "select-date"; date: string }
  | { type: "select-time"; time: string }
  | { type: "change-notes"; notes: string }
  | { type: "next" }
  | { type: "prev" }

const INITIAL_STATE: BookingState = {
  step: 1,
  menuId: null,
  staffId: null,
  date: null,
  time: null,
  notes: "",
}

export function canGoNext(state: BookingState): boolean {
  return state.step <= TOTAL_STEPS
}

function bookingReducer(state: BookingState, action: BookingAction): BookingState {
  switch (action.type) {
    case "select-menu":
      return { ...state, menuId: action.menuId }
    case "select-staff":
      return { ...state, staffId: action.staffId }
    case "select-date":
      return { ...state, date: action.date }
    case "select-time":
      return { ...state, time: action.time }
    case "change-notes":
      return { ...state, notes: action.notes }
    case "next":
      if (!canGoNext(state)) return state
      return { ...state, step: Math.min(state.step + 1, TOTAL_STEPS) }
    case "prev":
      return { ...state, step: Math.max(state.step - 1, 1) }
  }
}

type BookingContextValue = {
  shopId: string
  state: BookingState
  dispatch: React.Dispatch<BookingAction>
}

const BookingContext = createContext<BookingContextValue | null>(null)

export function BookingProvider({ shopId, children }: { shopId: string; children: React.ReactNode }) {
  const [state, dispatch] = useReducer(bookingReducer, INITIAL_STATE)

  return <BookingContext.Provider value={{ shopId, state, dispatch }}>{children}</BookingContext.Provider>
}

export function useBooking(): BookingContextValue {
  const context = useContext(BookingContext)
  if (!context) {
    throw new Error("useBooking は BookingProvider の内側で使ってください")
  }
  return context
}

BookingForm の作成

components/booking/BookingForm.tsx を作成します。

"use client"

import { Menu } from "@/types/menu";
import { Shop } from "@/types/shop";
import { Staff } from "@/types/staff";
import { BookingProvider, TOTAL_STEPS, canGoNext, useBooking } from "@/contexts/BookingContext";

type BookingFormProps = {
  shop: Shop
  menus: Menu[]
  staffs: Staff[]
}

export default function BookingForm({ shop, menus, staffs }: BookingFormProps) {
  return (
    <BookingProvider shopId={shop.id}>
      <BookingFlow />
    </BookingProvider>
  )
}

function BookingFlow() {
  const { state, dispatch } = useBooking()

  return (
    <div>
      {state.step === 1 && <div>STEP 1: メニューを選ぶ</div>}
      {state.step === 2 && <div>STEP 2: 日付・時間を選ぶ</div>}
      {state.step === 3 && <div>STEP 3: スタッフを選ぶ(任意)</div>}
      {state.step === 4 && <div>STEP 4: 確認して予約する</div>}

      <div className="my-4 flex justify-center gap-3">
        <button
          type="button"
          onClick={() => dispatch({ type: "prev" })}
          disabled={state.step === 1}
          className="rounded-xl border border-slate-300 px-5 py-3 text-sm font-medium disabled:opacity-40"
        >
          戻る
        </button>
        {state.step < TOTAL_STEPS ? (
          <button
            type="button"
            onClick={() => dispatch({ type: "next" })}
            disabled={!canGoNext(state)}
            className="rounded-xl border border-slate-300 px-5 py-3 text-sm font-medium disabled:opacity-40"
          >
            次へ
          </button>
        ) :
          <button
            type="button"
            className="rounded-xl border border-slate-300 px-5 py-3 text-sm font-medium disabled:opacity-40"
          >
            この内容で予約する
          </button>
        }
      </div>
    </div>
  )
}
部分説明
"use client"useReducer などのフックやクリック操作を使うため、Client Component にする
state.step === 1 && ...step が 1 のときだけ表示する
state.step < TOTAL_STEPS ? A : B最後のステップより前なら「次へ」、最後なら「この内容で予約する」を表示する
disabled={state.step === 1}最初のステップでは「戻る」を押せなくする
disabled={!canGoNext(state)}「次へ」を押せない状態のときは、ボタンを無効にする。今は常に押せる

「この内容で予約する」ボタンはまだ何もしません。送信処理は、あとで追加します。

なぜコンポーネントを 2 つに分けるのか

BookingForm の中で useBooking() を呼ぶと、エラーになります。 useContext() が値を取り出せるのは、Provider の 内側(子孫) のコンポーネントだけだからです。BookingForm 自身は Provider を返している側で、内側には含まれません。

// app/shop/[id]/book/page.tsx
...
return (
         // ここは useBooking() を実行できない
        <BookingForm
          shop={shop}
          menus={menus}
          staffs={staffs}
          candidateDates={getCandidateDates()}
          timeSlots={TIME_SLOTS}
        />
)
// components/BookingForm.tsx
export default function BookingForm({ shop, menus, staffs }: BookingFormProps) {
  // Provider で範囲指定
  return (
    <BookingProvider shopId={shop.id}>
      <BookingFlow />
    </BookingProvider>
  )
}

function BookingFlow({ menus, staffs, candidateDates, timeSlots }: BookingFlowProps) {
  // BookingFlow で useBooking() を実行
  const { shopId, state, dispatch } = useBooking()
  ...
}

BookingForm を配置

app/shop/[id]/book/page.tsx に BookingForm を配置します。メニューとスタッフは、店舗詳細ページと同じく Promise.all で並列に取得します。

import { notFound } from "next/navigation"

import SectionHeading from "@/components/SectionHeading"
import { getMenus, getShop, getStaffs } from "@/lib/services/shops"
import BookingForm from "@/components/booking/BookingForm"

type Props = {
  params: Promise<{ id: string }>
}

export default async function BookingPage({ params }: Props) {
  const { id } = await params

  const shop = await getShop(id)
  if (!shop) {
    notFound()
  }

  const [menus, staffs] = await Promise.all([getMenus(id), getStaffs(id)])

  return (
    <div>
      <SectionHeading
        eyebrow="Booking"
        title={`${shop.name} の予約`}
        description="メニュー・スタッフ・日時を選んで予約します。"
      />
      <div className="mt-8">
        <BookingForm shop={shop} menus={menus} staffs={staffs} />
      </div>
    </div>
  )
}

page.tsx は Server Component、BookingForm は Client Component です。データの取得はサーバー側で済ませ、取得結果を Props として Client Component に渡します。


動作確認

  • 「次へ」「戻る」ボタンで STEP 1〜4 が切り替わることを確認します。
  • STEP 1 では「戻る」が押せないこと、STEP 4 では「次へ」の代わりに「この内容で予約する」が表示されることを確認します。

まとめ

項目内容
"use client"フック・イベントを使うファイルに書く。境界線より下は Client Component として動く
Server / Client の使い分けデータ取得は Server Component、操作する部分だけを Client Component に切り出す
useReducerdispatch(action) を送り、reducer 関数が次の state を計算する状態管理フック
useState との使い分け管理する値・更新パターンが増えるほど useReducer の方が見通しが良くなる
ユニオン型の actiontype ごとに一緒に送る値を型で決め、送り間違いをコンパイル時に防ぐ
ContextProvider で囲んだ範囲に値を配り、useContext で取り出す
useBookingContext の取り出しと null チェックをまとめたカスタムフック
Provider と利用側の分離useContext は Provider の内側でしか使えないため、BookingForm と BookingFlow に分ける
Math.min / Math.max値が範囲を超えないように制限する
TOTAL_STEPSステップ数を定数にして、直し漏れを防ぐ
canGoNext「次へ」を押せるかの判定を 1 か所にまとめ、reducer とボタンの両方で使う