Created
November 22, 2020 22:55
-
-
Save jamiehaywood/dc5a3eb1804fd735f7033cfb1bb813b5 to your computer and use it in GitHub Desktop.
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 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