問題一覧に戻る
中級Context API
問題75: カスタムContextフック
より良いAPI設計のためにuseContextをラップするカスタムフックの作成方法を学びます。カスタムフックはprovider外でcontextが使用された場合のエラー処理を提供します。このパターンは開発体験を向上させ、ランタイムエラーを防ぎます。型安全性を持つ完全なcontext解決策のためにproviderとフックの両方をエクスポートします。
import React, { createContext, useContext, useState } from 'react';
{/* Contextを作成 */}
const ThemeContext = ();
{/* カスタムフック名 */}
function () {
const context = (ThemeContext);
if (!context) {
throw new Error(' must be used within ThemeProvider');
}
return context;
}
function ThemeProvider({ }) {
const [theme, setTheme] = useState('light');
const toggleTheme = () => setTheme(t => t === 'light' ? 'dark' : 'light');
return (
<ThemeContext.Provider value={{ theme, }}>
{children}
</ThemeContext.Provider>
);
}
function App() {
return (
{/* Providerでラップ */}
< >
<Button />
</ >
);
}
function Button() {
{/* カスタムフックを使用 */}
const { theme, toggleTheme } = ();
return <button onClick={toggleTheme}>{theme}</button>;
}
export default App;