- JavaScript
-
2024-08-02 - 更新:2024-08-04
通常、親コンポーネントから子コンポーネントにはpropsを使って情報を渡します。
しかし、深くネストされた下位コンポーネントに渡すには、メンテナンスのことも考えると非常に不便です。
コンテクスト(Context)を利用することで情報の受け渡しが簡単になります。
まずは基本の使い方から。
createContextでコンテクストオブジェクトを作成します。
createContextの引数はデフォルト値です。
import { createContext, useContext } from 'react';
const ThemeContext = createContext('light');
コンポーネントのトップレベルでuseContextを呼び出して、コンテクストを読み取ります。
function Button({ children }) {
const theme = useContext(ThemeContext);
const className = 'button-' + theme;
return (
<button className={className}>
{children}
</button>
);
}
コンテクストを上記のButtonに渡すには、該当のボタンあるいはその親コンポーネントのいずれかを、対応するコンテクストプロバイダでラップします。
export default function MyApp() {
return (
<ThemeContext.Provider value="dark">
<Form />
</ThemeContext.Provider>
)
}
function Form() {
// ... renders buttons inside ...
}
これでプロバイダとButtonの間にどれだけ多くのコンポーネントが挟まっていても関係なく情報を受け渡すことができます。




