Skip to content

Instantly share code, notes, and snippets.

@deadkff01
Created September 28, 2021 19:33
Show Gist options
  • Save deadkff01/4249091a0ef59c013ceac4bba91fbc14 to your computer and use it in GitHub Desktop.
Save deadkff01/4249091a0ef59c013ceac4bba91fbc14 to your computer and use it in GitHub Desktop.
Global context example
import {
createContext,
useReducer,
useMemo,
useContext,
ReactNode
} from "react";
type ContextProps = {
isLoading: boolean;
showError: boolean;
};
export type GlobalContextProps = {
state: ContextProps;
dispatch: (a: Action) => void;
};
const initialState: ContextProps = {
isLoading: false,
showError: false
};
export enum ACTIONS {
IS_LOADING = "IS_LOADING",
SHOW_ERROR = "SHOW_ERROR"
}
export type Action = {
type: ACTIONS;
payload: boolean;
};
export const GlobalContext = createContext<GlobalContextProps>({
state: initialState,
dispatch: () => {}
});
const reducer = (state: ContextProps, action: Action) => {
const { type, payload } = action;
switch (type) {
case ACTIONS.IS_LOADING:
return {
...state,
isLoading: payload
};
case ACTIONS.SHOW_ERROR:
return {
...state,
showError: payload
};
default:
return state;
}
};
interface IGlobalProvider {
children: ReactNode;
}
export const GlobalProvider = ({ children }: IGlobalProvider) => {
const [state, dispatch] = useReducer(reducer, initialState);
const store = useMemo(() => ({ state, dispatch }), [state, dispatch]);
return (
<GlobalContext.Provider value={store}>{children}</GlobalContext.Provider>
);
};
export const GlobalConsumer = GlobalContext.Consumer;
export const useGlobal = () => {
const context = useContext(GlobalContext);
if (!context) {
throw new Error("useGlobal must be used after an GlobalContext.Provider");
}
return context;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment