Created
September 14, 2022 12:01
-
-
Save CasperEngl/46d2df44be69ed80eed6ef39e82bbd70 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import React from 'react' | |
| type StrictContextReturn<T, U = T> = [React.Context<T>, () => U, T] | |
| export function createStrictContext<T>(options: { | |
| errorMessage?: string | |
| name?: string | |
| defaultValue?: T | |
| allowMissingProvider: true | |
| }): StrictContextReturn<T, T | undefined> | |
| export function createStrictContext<T>(options: { | |
| errorMessage?: string | |
| name?: string | |
| defaultValue?: T | |
| allowMissingProvider: false | |
| }): StrictContextReturn<T> | |
| export function createStrictContext<T>(options: { | |
| errorMessage?: string | |
| name?: string | |
| defaultValue?: T | |
| }): StrictContextReturn<T> | |
| /** | |
| * Inspiration {@link https://juliangaramendy.dev/blog/strict-react-context} | |
| */ | |
| export function createStrictContext<T>( | |
| options: { | |
| errorMessage?: string | |
| name?: string | |
| defaultValue?: T | |
| allowMissingProvider?: boolean | |
| } = {} | |
| ): StrictContextReturn<T> { | |
| const Context = React.createContext<T | undefined>(undefined) | |
| if (process.env.NODE_ENV === 'development') { | |
| Context.displayName = options.name | |
| } | |
| function useContext() { | |
| const context = React.useContext(Context) | |
| if (!options.allowMissingProvider && context === undefined) { | |
| throw new Error( | |
| options.errorMessage || | |
| `${Context.displayName || ''} Context Provider is missing` | |
| ) | |
| } | |
| return context | |
| } | |
| return [Context, useContext, options.defaultValue] as StrictContextReturn<T> | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment