Skip to content

Instantly share code, notes, and snippets.

@CasperEngl
Created September 14, 2022 12:01
Show Gist options
  • Select an option

  • Save CasperEngl/46d2df44be69ed80eed6ef39e82bbd70 to your computer and use it in GitHub Desktop.

Select an option

Save CasperEngl/46d2df44be69ed80eed6ef39e82bbd70 to your computer and use it in GitHub Desktop.
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