Created
November 20, 2019 03:10
-
-
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
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
// 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