buildContext
buildContext は、React のコンテキストを定義する際の繰り返しのコードを減らすヘルパー関数です。
インターフェース
ts
function buildContext<ContextValuesType extends object>(
contextName: string,
defaultContextValues?: ContextValuesType
): [
Provider: (props: ProviderProps<ContextValuesType>) => JSX.Element,
useContext: () => ContextValuesType,
];パラメータ
- contextNamerequired · string
コンテキストの名前。
- defaultContextValuesContextValuesType
コンテキストに渡すデフォルト値。
戻り値
- [Provider: (props: ProviderProps<ContextValuesType>) => JSX.Element, useContext: () => ContextValuesType]
次の要素を持つタプル。
- Provider(props: ProviderProps<ContextValuesType>) => JSX.Element
コンテキストを提供するコンポーネント。
- useContext() => ContextValuesType
コンテキストを使用するフック。
- Provider(props: ProviderProps<ContextValuesType>) => JSX.Element
使用例
tsx
const [Provider, useContext] = buildContext<{ title: string }>('TestContext', {
title: 'Default title',
});
function Inner() {
const { title } = useContext();
return <div>{title}</div>;
}
function Page() {
return (
<Provider title="Hello">
<Inner />
</Provider>
);
}