Skip to content

Instantly share code, notes, and snippets.

@phdesign
Created September 5, 2022 05:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save phdesign/7af4e217d90d0824f9450ef27286cc57 to your computer and use it in GitHub Desktop.
Save phdesign/7af4e217d90d0824f9450ef27286cc57 to your computer and use it in GitHub Desktop.
A wrapper around `React.useContext` that throws an error if the context value is `undefined`.
import { useContext } from "react"
/**
* A wrapper around `React.useContext` that throws an error if the context
* value is `undefined`, indicating that the component is not wrapped in the
* context provider.
* @param {React.Context} context
* @return {any} The context value.
*/
export const useSafeContext = (context) => {
const value = useContext(context)
if (value === undefined) {
throw new Error(
"Context value is undefined, are you missing a context provider?"
)
}
return value
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment