Skip to content

Instantly share code, notes, and snippets.

@jasmo2
Last active October 27, 2021 23:27
Show Gist options
  • Save jasmo2/1775785888ed75c8588edc1e51c3a6c2 to your computer and use it in GitHub Desktop.
Save jasmo2/1775785888ed75c8588edc1e51c3a6c2 to your computer and use it in GitHub Desktop.
import { useContext } from "react"
export function useContextFactory<T>(name: string, context: React.Context<T>) {
return () => {
const ctx = useContext(context)
if (ctx === undefined) {
throw new Error(
`use${name}Context must be used withing a ${name}ContextProvider.`
)
}
return ctx as NonNullable<T>
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment