import { createContext, PropsWithChildren, useContext, useState } from 'react'; interface IContext { getValue: (key: string) => T | undefined; setValue: (key: string, value: T) => void; } const AppStateContext = createContext(undefined); const AppStateContextProvider = ({ children }: PropsWithChildren<{}>) => { const [appState, setAppState] = useState>({}); const getValue = (key: string) => appState[key] as T; const setValue = (key: string, value: T) => setAppState((prevAppState) => ({ ...prevAppState, [key]: value })); return ( {children} ); }; const useAppState = (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(key), (value: T) => setValue(key, value)]; }; export { AppStateContextProvider, useAppState };