React のカスタム Hooks は、コンポーネントロジックを再利用可能な関数に抽出するための強力な機能です。これにより、複数のコンポーネント間でコードの重複を避け、状態や副作用のロジックを共有することができます。
カスタム Hooks の作成と使用
カスタム Hooks は通常、"use" で始まる名前が付けられます。以下にカスタム Hooks を作成して使用する基本的な方法を示します。
例 1: useCounter カスタム Hook
ここでは、簡単なカウンター用のカスタム Hook を作成します。
カスタム Hook の作成
まず、新しいファイル useCounter.js にカスタム Hook を作成します。
import { useState } from 'react';
const useCounter = (initialValue = 0) => {
const [count, setCount] = useState(initialValue);
const increment = () => setCount(count + 1);
const decrement = () => setCount(count - 1);
const reset = () => setCount(initialValue);
return { count, increment, decrement, reset };
};
export default useCounter;
カスタム Hook の使用
次に、コンポーネントで useCounter カスタム Hook を使用します。
import React from 'react';
import useCounter from './useCounter';
const CounterComponent = () => {
const { count, increment, decrement, reset } = useCounter(10);
return (
<div>
<h1>Count: {count}</h1>
<button onClick={increment}>Increment</button>
<button onClick={decrement}>Decrement</button>
<button onClick={reset}>Reset</button>
</div>
);
};
export default CounterComponent;
例 2: useFetch カスタム Hook
次に、データを取得するためのカスタム Hook を作成します。
カスタム Hook の作成
新しいファイル useFetch.js に useFetch カスタム Hook を作成します
import { useState, useEffect } from 'react';
const useFetch = (url) => {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
const fetchData = async () => {
try {
const response = await fetch(url);
if (!response.ok) {
throw new Error('Network response was not ok');
}
const result = await response.json();
setData(result);
} catch (error) {
setError(error);
} finally {
setLoading(false);
}
};
fetchData();
}, [url]);
return { data, loading, error };
};
export default useFetch;
カスタム Hook の使用
次に、コンポーネントで useFetch カスタム Hook を使用します。
import React from 'react';
import useFetch from './useFetch';
const DataFetchingComponent = () => {
const { data, loading, error } = useFetch('https://api.example.com/data');
if (loading) return <div>Loading...</div>;
if (error) return <div>Error: {error.message}</div>;
return (
<div>
<h1>Fetched Data:</h1>
<pre>{JSON.stringify(data, null, 2)}</pre>
</div>
);
};
export default DataFetchingComponent;
例 3: usePrevious カスタム Hook
この Hook は、以前のレンダリングサイクルの状態値を取得するためのものです。
カスタム Hook の作成
新しいファイル usePrevious.js に usePrevious カスタム Hook を作成します
import { useRef, useEffect } from 'react';
const usePrevious = (value) => {
const ref = useRef();
useEffect(() => {
ref.current = value;
}, [value]);
return ref.current;
};
export default usePrevious;
カスタム Hook の使用
次に、コンポーネントで usePrevious カスタム Hook を使用します。
import React, { useState } from 'react';
import usePrevious from './usePrevious';
const PreviousValueComponent = () => {
const [count, setCount] = useState(0);
const prevCount = usePrevious(count);
return (
<div>
<h1>Current Count: {count}</h1>
<h2>Previous Count: {prevCount}</h2>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
};
export default PreviousValueComponent;
カスタム Hooks は、React コンポーネントの状態ロジックを再利用可能な関数に抽出するための強力なツールです。