問題一覧に戻る
中級Context API
問題69: Context作成
createContextを使用してContextを作成し、デフォルト値を設定する方法を学びます。Contextはコンポーネントツリーを通してデータを共有する仕組みで、propsドリリングを避けられます。デフォルト値はProviderがない場合に使用されます。useContextフックでContextの値を取得し、グローバルなテーマ、認証情報、言語設定などの共有に活用できます。
import React, { createContext, useContext } from 'react';
{/* Contextを作成 */}
const ThemeContext = ('light');
function Button() {
{/* Contextを使用 */}
const theme = (ThemeContext);
return (
<button style={{ background: theme === 'dark' ? '#333' : '#fff' }}>
{theme} theme
</button>
);
}
function App() {
return <Button />;
}
export default App;