Created
April 29, 2022 11:25
-
-
Save timiles/5fe14d4d27d98b480196c9442b222d13 to your computer and use it in GitHub Desktop.
Global app state using React Context
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 { createContext, PropsWithChildren, useContext, useState } from 'react'; | |
interface IContext { | |
getValue: <T>(key: string) => T | undefined; | |
setValue: <T>(key: string, value: T) => void; | |
} | |
const AppStateContext = createContext<IContext | undefined>(undefined); | |
const AppStateContextProvider = ({ children }: PropsWithChildren<{}>) => { | |
const [appState, setAppState] = useState<Record<string, any>>({}); | |
const getValue = <T,>(key: string) => appState[key] as T; | |
const setValue = <T,>(key: string, value: T) => | |
setAppState((prevAppState) => ({ ...prevAppState, [key]: value })); | |
return ( | |
<AppStateContext.Provider value={{ getValue, setValue }}>{children}</AppStateContext.Provider> | |
); | |
}; | |
const useAppState = <T,>(key: string): [T | undefined, (value: T) => void] => { | |
const context = useContext(AppStateContext); | |
if (!context) { | |
// This is an error message for the developer | |
throw new Error('useAppState must be used inside a AppStateContextProvider.'); | |
} | |
const { getValue, setValue } = context; | |
return [getValue<T>(key), (value: T) => setValue(key, value)]; | |
}; | |
export { AppStateContextProvider, useAppState }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment