3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【React】カスタムフックとは

Posted at

この記事の目的

  • Reactの理解とアウトプット、振り返り用
  • Reactでよく使われている基本的な技術を言語化できるようする

カスタムフックとは

複数のコンポーネントの中に存在する共通の処理を取り出して作成した関数のこと。汎用的なカスタムフックを作成することで作成したアプリ>ケーション内だけでなく別のアプリケーションでも再利用することが可能になります。

簡単に言うと、同じ処理書くのは無駄だし読みずらいし、どっかでまとめちゃおうって話。まとめたら必要なときに呼び出せばいいじゃんってこと。
カスタムフックって言葉を使っているけど、要はただの関数のこと

メリット

  • 使いまわしがきく
  • テストが簡単
  • コードが読みやすくなる
  • hooksの各機能を使用できる(useState,useEffect,useMemoなど)

カスタムフックのルール

  • フックを含む関数であること(useState,useEffect,useMemoなど)
  • 命名はuse〇〇とする
  • hooksというディレクトリを切って管理していくのが一般的

カスタムフック使用例

例として「全ユーザー一覧を取得するカスタムフック」(./hooks/useAllUsers.ts)を作成して、作成したカスタムフックを呼び出し取得したユーザ情報を表示する(./App.tsx)といったことをしていきます。

ユーザ情報を表示するファイル(カスタムフックを呼び出し)

./App.tsx
import "./styles.css";
import { UserCard } from "./components/UserCard";
import { useAllUsers } from "./hooks/useAllUsers";

export default function App() {
  // カスタムフックを呼び出し、返却値を受け取る
  const { getUsers, userProfiles, loading, error } = useAllUsers();
  const onClickFetchUser = () => getUsers();

  return (
    <div className="App">
      <button onClick={onClickFetchUser}>データ取得</button>
      <br />
      {error ? (
        <p style={{ color: "red" }}>データの取得に失敗しました</p>
      ) : loading ? (
        <p>Loading...</p>
      ) : (
        <>
          {userProfiles.map((user) => (
            <UserCard key={user.id} user={user} />
          ))}
        </>
      )}
    </div>
  );
}

全ユーザー一覧を取得するカスタムフック

./hooks/useAllUsers.ts
import axios from "axios";
import { useState } from "react";
import { UserProfile } from "../types/userProfile";
import { User } from "../types/api/user";

// 全ユーザー一覧を取得するカスタムフック
export const useAllUsers = () => {
  const [userProfiles, setUserProfiles] = useState<Array<UserProfile>>([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(false);

  const getUsers = () => {
    setLoading(true);
    setError(false);

    axios
      .get<Array<User>>("https://jsonplaceholder.typicode.com/users")
      .then((res) => {
        const data = res.data.map((user) => ({
          id: user.id,
          name: `${user.name}(${user.username})`,
          email: user.email,
          address: `${user.address.city}${user.address.suite}${user.address.street}`
        }));
        setUserProfiles(data);
      })
      .catch((err) => {
        setError(true);
      })
      .finally(() => {
        setLoading(false);
      });
  };

  // 他のコンポーネントでカスタムフックで定義したStateや関数が使用できるように、returnで返却する
  return { getUsers, userProfiles, loading, error };
};

カスタムフックまとめ

  • ルールは「フックを含む関数」「命名はuse〇〇」「hooksディレクトリ内で管理」
  • メリット:「再利用」「テスト容易」「コード読みやすい」「hooksの各機能を使用可能」
  • カスタムフックで定義したStateや関数が使用できるように、returnで返却する
3
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?