読み方のヒント

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

第4節 カスタムフックで処理をまとめる

4.1 カスタムフックを作る

第3節の読み込みの処理を、useProducts という関数にまとめます。

// src/hooks/useProducts.ts
import { useEffect, useState } from "react";
import type { Product } from "../types.ts";

type LoadState =
  | { status: "loading" }
  | { status: "success"; products: Product[] }
  | { status: "error"; message: string };

export const useProducts = (): LoadState => {
  const [state, setState] = useState<LoadState>({ status: "loading" });

  useEffect(() => {
    let ignore = false;
    const load = async () => {
      try {
        const response = await fetch("/products.json");
        if (!response.ok) throw new Error(String(response.status));
        const products = (await response.json()) as Product[];
        if (!ignore) setState({ status: "success", products });
      } catch {
        if (!ignore) setState({ status: "error", message: "商品を読み込めませんでした" });
      }
    };
    load();
    return () => {
      ignore = true;
    };
  }, []);

  return state;
};
export const ProductCatalog = () => {
  const state = useProducts();

  if (state.status === "loading") return <p>商品を読み込んでいます…</p>;
  if (state.status === "error") return <p>{state.message}</p>;
  return <ProductList products={state.products} />;
};
決まり理由
名前は use で始める中で useState などを使う関数だと分かり、React の決まりの確認ができる
部品と同じく、いちばん上で呼ぶ中のフックの呼ばれる順番が変わらないようにする
戻り値の型を決める使う側が、何が返るかを型で知れる

カスタムフックがまとめるのは処理で、state は呼んだ部品ごとに別になります。2つの部品で useProducts() を呼ぶと、それぞれが別の state を持ち、別々に読み込みます。

15 / 17