Skip to content

Instantly share code, notes, and snippets.

@Xevion
Created October 26, 2022 02:11
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 Xevion/3aec5dcee80ec290b93bbfbbc8b380a6 to your computer and use it in GitHub Desktop.
Save Xevion/3aec5dcee80ec290b93bbfbbc8b380a6 to your computer and use it in GitHub Desktop.
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