Skip to content

buildContext

buildContext is a helper function that reduces repetitive code when defining React Context.

Interface

ts
function buildContext(
  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]

    tuple of the form :

    • Provider(props: ProviderProps<ContextValuesType>) => JSX.Element

      The component that provides the context.

    • useContext() => ContextValuesType

      The hook that uses the context.

Example

tsx
const [Provider, useContext] = buildContext<{ title: string }>(
  'TestContext',
  null
);

function Inner() {
  const { title } = useContext();
  return <div>{title}</div>;
}

function Page() {
  return (
    <Provider title="Hello">
      <Inner />
    </Provider>
  );
}

Released under the MIT License.