Skip to content

Instantly share code, notes, and snippets.

@drumnickydrum
Created December 30, 2022 21:12
Show Gist options
  • Save drumnickydrum/53a33345eb6efdb060fe22e07a889ebf to your computer and use it in GitHub Desktop.
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
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