Created
December 14, 2020 09:08
-
-
Save VehpuS/5e6c4d4b171ecfed82be314422007add to your computer and use it in GitHub Desktop.
A template for a React context with a safe hook accessor
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 React from "react"; | |
export interface TemplateContextProps { | |
templateValue: any; | |
} | |
export const TemplateContext = React.createContext<TemplateContextProps | undefined>(undefined); | |
export const TemplateContextProvider: React.FunctionComponent<{ | |
initialTemplateValue: any | |
}> = ({ | |
initialTemplateValue, children | |
}) => { | |
const [templateValue, setTemplateValue,] = React.useState(initialTemplateValue); | |
const contextValue = React.useMemo(() => ({ | |
templateValue, | |
}), [ | |
templateValue, | |
]); | |
return <TemplateContext.Provider | |
value={contextValue} | |
children={children} | |
/>; | |
} | |
export const useTemplateContext = (): TemplateContextProps => { | |
const contextValue = React.useContext(TemplateContext); | |
if (!contextValue) { | |
throw new Error("Tried to use template context from outside the provider"); | |
} | |
return contextValue; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment