UNPKG

@navikt/ds-react

Version:

React components from the Norwegian Labour and Welfare Administration.

41 lines (40 loc) 1.41 kB
/** * Custom createStrictContext to consolidate context-implementation across the system. * Unlike React's createContext, this throws an error by default when used outside a provider. * * Inspired by: * - https://github.com/radix-ui/primitives/blob/main/packages/react/context/src/createContext.tsx * - https://github.com/chakra-ui/chakra-ui/blob/5ec0be610b5a69afba01a9c22365155c1b519136/packages/hooks/context/src/index.ts */ import React from "react"; type ProviderProps<T> = T & { children: React.ReactNode; ref?: never; }; /** * When defaultValue is provided, context is always defined. * The hook will always return T (no strict parameter needed). */ declare function createStrictContext<T>(options: { name: string; errorMessage?: string; defaultValue: T; }): { Provider: React.FC<ProviderProps<T>>; useContext: () => T; }; /** * When no defaultValue is provided, context may be undefined. * The hook accepts an optional `strict` parameter (default: true). * - strict=true (default): throws if undefined, returns T * - strict=false: returns T | undefined */ declare function createStrictContext<T>(options: { name: string; errorMessage?: string; defaultValue?: undefined; }): { Provider: React.FC<ProviderProps<T>>; useContext: <S extends boolean = true>(strict?: S) => S extends true ? T : T | undefined; }; export { createStrictContext };