Created
February 24, 2023 09:47
-
-
Save louis-young/138f77a1274c84952717c9a31c69a583 to your computer and use it in GitHub Desktop.
Safe context hook creator function
This file contains hidden or 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 { type Context, useContext } from "react"; | |
import { invariant } from "../invariant"; | |
export const createSafeContextHook = <TContextValue>( | |
context: Context<TContextValue>, | |
displayName: string | |
) => { | |
return () => { | |
const contextValue = useContext(context); | |
invariant( | |
contextValue, | |
`${displayName} must be used within a ${displayName}Provider.` | |
); | |
return contextValue; | |
}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment