Contextの値を購読する。Providerで囲まれた最も近い祖先コンポーネントの値を返す。props drillingを解消するのに使う。
const value = useContext(SomeContext)
interface ThemeContextType {
theme: 'light' | 'dark';
toggle: () => void;
}
const ThemeContext = createContext<ThemeContextType | null>(null);
// null チェックを避けるカスタムフック
const useTheme = () => {
const ctx = useContext(ThemeContext);
if (!ctx) throw new Error('ThemeProviderが必要です');
return ctx;
};import { createContext, useContext, useState } from 'react';
// 1. Contextを作成
const ThemeContext = createContext<{
theme: 'light' | 'dark';
toggle: () => void;
} | null>(null);
// 2. Providerを作成
export function ThemeProvider({ children }: { children: React.ReactNode }) {
const [theme, setTheme] = useState<'light' | 'dark'>('light');
const toggle = () => setTheme(t => t === 'light' ? 'dark' : 'light');
return (
<ThemeContext.Provider value={{ theme, toggle }}>
{children}
</ThemeContext.Provider>
);
}
// 3. カスタムフックで安全に使う
function useTheme() {
const ctx = useContext(ThemeContext);
if (!ctx) throw new Error('ThemeProviderでラップしてください');
return ctx;
}
// 4. 任意のコンポーネントで消費
function Header() {
const { theme, toggle } = useTheme();
return <button onClick={toggle}>{theme === 'light' ? '🌙' : '☀️'}</button>;
}Contextが更新されると、その値を使っているすべてのコンポーネントが再レンダーされる。頻繁に変わる値は別Contextに分離するか、useReducerと組み合わせる。