Skip to content

Instantly share code, notes, and snippets.

@wgao19
Created November 20, 2019 03:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wgao19/fd7f42e0c4190588220ff4a5546ee203 to your computer and use it in GitHub Desktop.
Save wgao19/fd7f42e0c4190588220ff4a5546ee203 to your computer and use it in GitHub Desktop.
tweaked [context example from react typescript cheatsheet](https://github.com/typescript-cheatsheets/react-typescript-cheatsheet#context) for own usage
// https://github.com/typescript-cheatsheets/react-typescript-cheatsheet#context
import * as React from 'react';
function createContext<ContextType>(defaultValue?: ContextType) {
const Context = React.createContext<ContextType | undefined>(defaultValue);
const useContext = () => {
const contextValue = React.useContext(Context);
if (!contextValue)
throw new Error('`useContext` must be inside a Provider with a value.');
return contextValue;
};
const ContextProvider = ({
children,
value,
}: {
children?: React.ReactChild;
value: ContextType;
}) => {
return <Context.Provider value={value}>{children}</Context.Provider>;
};
return [useContext, ContextProvider] as const;
}
export default createContext;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment