buildContext
buildContext es una función auxiliar que reduce el código repetitivo al definir un contexto de React.
Interfaz
ts
function buildContext<ContextValuesType extends object>(
contextName: string,
defaultContextValues?: ContextValuesType
): [
Provider: (props: ProviderProps<ContextValuesType>) => JSX.Element,
useContext: () => ContextValuesType,
];Parámetros
- contextNamerequired · string
El nombre del contexto.
- defaultContextValuesContextValuesType
Los valores predeterminados que pasas al contexto.
Valor de retorno
- [Provider: (props: ProviderProps<ContextValuesType>) => JSX.Element, useContext: () => ContextValuesType]
Una tupla con la siguiente forma:
- Provider(props: ProviderProps<ContextValuesType>) => JSX.Element
El componente que proporciona el contexto.
- useContext() => ContextValuesType
El Hook que usa el contexto.
- Provider(props: ProviderProps<ContextValuesType>) => JSX.Element
Ejemplo
tsx
const [Provider, useContext] = buildContext<{ title: string }>('TestContext', {
title: 'Título predeterminado',
});
function Inner() {
const { title } = useContext();
return <div>{title}</div>;
}
function Page() {
return (
<Provider title="Hola">
<Inner />
</Provider>
);
}