Skip to content

Instantly share code, notes, and snippets.

@VehpuS
Created December 14, 2020 09:08
Show Gist options
  • Save VehpuS/5e6c4d4b171ecfed82be314422007add to your computer and use it in GitHub Desktop.
Save VehpuS/5e6c4d4b171ecfed82be314422007add to your computer and use it in GitHub Desktop.
A template for a React context with a safe hook accessor
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