Created
February 14, 2022 13:52
-
-
Save kylelambert101/0d1a89ca391b1c9ee83d62f6f2810ab7 to your computer and use it in GitHub Desktop.
React -> Simple Context
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 * as React from 'react'; | |
export interface SimpleContextType { | |
userName: string | undefined; | |
setUserName: (userName: string | undefined) => void; | |
} | |
export const SimpleContext = React.createContext<SimpleContextType>({ userName: undefined, setUserName: () => undefined }); | |
export const SimpleContextProvider = ({ children }: { children: React.ReactNode }): React.ReactElement => { | |
const [userName, setUserName] = React.useState<string | undefined>(); | |
const state = React.useMemo(() => ({ userName, setUserName }), [userName]); | |
return <SimpleContext.Provider value={state}>{children}</SimpleContext.Provider>; | |
}; | |
export const useSimpleContext = (): SimpleContextType => React.useContext(SimpleContext); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment