Last active
August 30, 2020 02:23
-
-
Save GabeDuarteM/3a48f17d997ec004dcc0dfc505d9bde2 to your computer and use it in GitHub Desktop.
React context utils
This file contains hidden or 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 function createContext<ContextValueType extends {} | null>(): readonly [ | |
| () => ContextValueType, | |
| React.Provider<ContextValueType | undefined>, | |
| ] { | |
| const context = React.createContext<ContextValueType | undefined>( | |
| undefined, | |
| ); | |
| function useContext(): ContextValueType { | |
| const value = React.useContext(context); | |
| if (value === undefined) { | |
| throw new Error( | |
| 'useContext must be inside a Provider with a value', | |
| ); | |
| } | |
| return value; | |
| } | |
| return [useContext, context.Provider] as const; | |
| } |
This file contains hidden or 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"; | |
| import createContext from './createContext'; | |
| const [useUserInfoContext, UserInfoProviderInternal] = createContext< | |
| string | |
| >(); | |
| export { useUserInfoContext }; | |
| export const UserInfoProvider: React.FC = ({ children }) => { | |
| const value = "" | |
| return ( | |
| <UserInfoProviderInternal | |
| value={value} | |
| > | |
| {children} | |
| </UserInfoProviderInternal> | |
| ); | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment