Custom Hook とは?
Custom Hooksは、再利用可能なフック処理を関数として抽出し、独立させるもの。
命名規則
Custom Hookの命名は「use
」で始めるのが慣例。
例:useFetch
, useLocalStorage
サンプルコード
hooks/useCounter.ts
import { useEffect, useRef, useState } from 'react';
export const useCountUp = (): [number, () => void, () => void] => {
const [time, setTime] = useState<number>(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();
};
const stop = () => {
setTime(-1);
if (intervalIdRef.current) {
clearInterval(intervalIdRef.current);
intervalIdRef.current = null;
}
};
useEffect(() => {
setTimer();
return () => {
if (intervalIdRef.current) {
clearInterval(intervalIdRef.current);
}
};
}, []);
return [time, reset, stop];
};
インポート
カスタムフックを利用する場合は、コンポーネントで対象のフック処理をインポートして利用する。
import React from 'react';
import useCounter from './hooks/useCounter';
function CounterComponent() {
const [time, reset, stop] = useCounter();
return (
<div>
<p>Count: {time}</p>
<button onClick={reset}>Reset</button>
<button onClick={stop}>Stop</button>
</div>
);
}
export default CounterComponent;
Hooksを独立させる理由
Custom Hookは特定のコンポーネントに依存しないように設計すると、他のコンポーネントでも再利用が容易になる。
これにより、アプリケーション全体のコードの一貫性と保守性の向上につながる。