carbon-react
Version:
A library of reusable React components for easily building user interfaces.
32 lines (31 loc) • 1.15 kB
TypeScript
import React from "react";
type CreateStrictContextArgs<ContextType> = {
/** The display name of the context. */
name?: string;
/** Error message to log if context is accessed outside its provider. */
errorMessage: string;
/** Default value to return if context is accessed outside its provider. */
defaultValue: ContextType;
};
type CreateStrictContextReturn<ContextType> = readonly [
React.Provider<ContextType | null>,
() => ContextType
];
/**
* Creates a React context with a provider and a hook for accessing the context.
* Logs an error and returns a default value if the hook is used outside of the provider.
*
* @example
*
* ```tsx
* const [ListProvider, useList] = createStrictContext<{ size: number }>({
* name: "ListContext",
* errorMessage: "ListContext is undefined. Make sure to wrap your component with <ListProvider />",
* defaultValue: {
* size: 0,
* },
* });
* ```
*/
declare function createStrictContext<ContextType>({ name, errorMessage, defaultValue, }: CreateStrictContextArgs<ContextType>): CreateStrictContextReturn<ContextType>;
export default createStrictContext;