Created
December 30, 2022 21:12
-
-
Save drumnickydrum/53a33345eb6efdb060fe22e07a889ebf to your computer and use it in GitHub Desktop.
[React: Context Boilerplate] Sets up a hook to use context without the undefined initialization value #react #context
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
type FooContextType = { some: 'type' }; | |
export const FooContext = React.createContext<FooContextType | undefined>( | |
undefined | |
); | |
export function FooProvider(props: { children: React.ReactNode }): JSX.Element { | |
const value = useFoo(); | |
return ( | |
<FooContext.Provider value={value}>{props.children}</FooContext.Provider> | |
); | |
} | |
export function useFooContext(): FooContextType { | |
const context = React.useContext(FooContext); | |
if (!context) { | |
throw new Error('useFooContext must be used within a FooProvider'); | |
} | |
return context; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment