buildContext
buildContext is a helper function that reduces repetitive code when defining React Context.
Interface
ts
function buildContext<ContextValuesType extends object>(
contextName: string,
defaultContextValues?: ContextValuesType
): [
Provider: (props: ProviderProps<ContextValuesType>) => JSX.Element,
useContext: () => ContextValuesType,
];Parameters
- contextNamerequired · string
The name of the context.
- defaultContextValuesContextValuesType
The default values to be passed to the context.
Return Value
- [Provider: (props: ProviderProps<ContextValuesType>) => JSX.Element, useContext: () => ContextValuesType]
A tuple of the form :
- Provider(props: ProviderProps<ContextValuesType>) => JSX.Element
The component that provides the context.
- useContext() => ContextValuesType
The hook that uses the context.
- Provider(props: ProviderProps<ContextValuesType>) => JSX.Element
Example
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>
);
}