0
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?

[React] Custom Hookを理解する!

Last updated at Posted at 2024-05-14

Custom Hook とは?

Custom Hookは、再利用可能なフック処理を関数として抽出し、独立させる機能。

噛み砕くと、状態や副作用をコンポーネントとは別のファイルに定義して、コンポーネントでそれらをインポートします。

命名規則

Custom Hookの命名は「use」で始めるのが慣例です。
例:useFetch.ts, useLocalStorage.ts

bulletproof-reactでは、hooksディレクトリにファイルを配置します。

サンプルコード

タイマーの状態、副作用をカスタムフックとして、コンポーネントから分離します。

hooks/useTimer.ts

import { useEffect, useRef, useState } from 'react';

export const useCountUp = (): [number, () => void, () => void] => {
  const [time, setTime] = useState(0);
  const intervalIdRef = useRef<NodeJS.Timeout | null>(null);
  
  const setTimer = () => {
    if (intervalIdRef.current !== null) {
      clearInterval(intervalIdRef.current);
    }

    intervalIdRef.current = setInterval(() => {
      setTime((time) => time + 1);
    }, 1000);
  };

  const reset = () => {
    setTime(0);
    setTimer();
  };

  useEffect(() => {
    setTimer();

    return () => {
      if (intervalIdRef.current) {
        clearInterval(intervalIdRef.current);
      }
    };
  }, []);

  return [time, reset];
};

インポート

カスタムフックを利用する場合は、コンポーネントで対象のフック処理をインポートして利用する。

import React from 'react';
import useCounter from './hooks/useCounter';

function CounterComponent() {
  const [time, reset] = useCounter();

  return (
    <div>
      <p>Count: {time}</p>
      <button onClick={reset}>Reset</button>
    </div>
  );
}

export default CounterComponent;

Hooksを独立させる理由

Custom Hookは特定のコンポーネントに依存しないように設計すると、他のコンポーネントでも再利用が容易になります。

これにより、アプリケーション全体のコードの一貫性と保守性の向上につながります。

参考記事

0
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
0
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?