Skip to content

Instantly share code, notes, and snippets.

@jamiehaywood
Created November 22, 2020 22:55
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 jamiehaywood/dc5a3eb1804fd735f7033cfb1bb813b5 to your computer and use it in GitHub Desktop.
Save jamiehaywood/dc5a3eb1804fd735f7033cfb1bb813b5 to your computer and use it in GitHub Desktop.
import React, { createContext, useState, useContext, Dispatch, SetStateAction } from "react";
export interface GlobalStateInterface {
firstname: string;
lastname: string;
age: string;
}
const GlobalStateContext = createContext({
state: {} as Partial<GlobalStateInterface>,
setState: {} as Dispatch<SetStateAction<Partial<GlobalStateInterface>>>,
});
const GlobalStateProvider = ({
children,
value = {} as GlobalStateInterface,
}: {
children: React.ReactNode;
value?: Partial<GlobalStateInterface>;
}) => {
const [state, setState] = useState(value);
return (
<GlobalStateContext.Provider value={{ state, setState }}>
{children}
</GlobalStateContext.Provider>
);
};
const useGlobalState = () => {
const context = useContext(GlobalStateContext);
if (!context) {
throw new Error("useGlobalState must be used within a GlobalStateContext");
}
return context;
};
export { GlobalStateProvider, useGlobalState };
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment