Created
October 26, 2022 02:11
-
-
Save Xevion/3aec5dcee80ec290b93bbfbbc8b380a6 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 { createContext, Dispatch, ReactNode, useContext, useReducer } from "react"; | |
export interface GlobalContextProps { | |
loggedIn: boolean; | |
background: boolean; | |
} | |
export interface GlobalContextAction { | |
type: string; | |
value: any; | |
} | |
export const globalContextReducer = (state: GlobalContextProps, action: GlobalContextAction) => { | |
switch (action.type) { | |
case "background": | |
state.background = action.value; | |
return state; | |
default: | |
return state; | |
} | |
}; | |
export const initialState = { loggedIn: false, background: true }; | |
const dispatch: Dispatch<GlobalContextAction> = () => null; | |
export const GlobalContext = createContext([initialState, dispatch]); | |
export const useGlobalContext = () => { | |
return useContext(GlobalContext); | |
}; | |
interface GlobalProviderProps { | |
children: ReactNode; | |
} | |
export const GlobalProvider = ({ children }: GlobalProviderProps) => { | |
const reducer = useReducer(globalContextReducer, initialState); | |
return <GlobalContext.Provider value={reducer}>{children}</GlobalContext.Provider>; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment