Created
August 9, 2020 14:07
-
-
Save JulianG/9aa3e0d299e0eb35637cd9d69540d4f9 to your computer and use it in GitHub Desktop.
Create React Strict Context
This file contains 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'; | |
export function createStrictContext(options = {}) { | |
const Context = React.createContext(undefined); | |
Context.displayName = options.name; | |
function useContext() { | |
const context = React.useContext(Context); | |
if (!context) { | |
throw new Error(options.errorMessage || `${name || ''} Context Provider is missing`); | |
} | |
return context; | |
} | |
return [Context.Provider, useContext]; | |
} |
This file contains 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' | |
export function createStrictContext<T>( | |
options: { | |
errorMessage?: string | |
name?: string | |
} = {} | |
) { | |
const Context = React.createContext<T | undefined>(undefined) | |
Context.displayName = options.name | |
function useContext() { | |
const context = React.useContext(Context) | |
if (!context) { | |
throw new Error(options.errorMessage || `${name || ''} Context Provider is missing`) | |
} | |
return context | |
} | |
return [Context.Provider, useContext] as [React.Provider<T>, () => T] | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment