Skip to content

Instantly share code, notes, and snippets.

@timiles
Created April 29, 2022 11:25
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 timiles/5fe14d4d27d98b480196c9442b222d13 to your computer and use it in GitHub Desktop.
Save timiles/5fe14d4d27d98b480196c9442b222d13 to your computer and use it in GitHub Desktop.
Global app state using React Context
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