Created
September 5, 2022 05:32
-
-
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`.
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 { 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