Skip to content

Instantly share code, notes, and snippets.

@LishuGupta652
Last active December 27, 2021 08:34
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 LishuGupta652/1c66ace186f991b1e2328d69d549f5bf to your computer and use it in GitHub Desktop.
Save LishuGupta652/1c66ace186f991b1e2328d69d549f5bf to your computer and use it in GitHub Desktop.
Global Reducer + context
import React, { createContext, useReducer, useContext } from "react";
// Define the context
const GlobalStateContext = createContext();
const GlobalDispatchContext = createContext();
// Reducer
const globalReducer = (state, action) => {
switch (action.type) {
case "TOGGLE_THEME": {
return {
...state,
currentTheme: action.theme,
};
}
case "CURSOR_TYPE": {
return {
...state,
cursorType: action.cursorType,
};
}
default: {
throw new Error(`Unhandled action type: ${action.type}`);
}
}
};
export const GlobalProvider = ({ children }) => {
const [state, dispatch] = useReducer(globalReducer, {
currentTheme: window.localStorage.getItem("theme") || "dark",
cursorType: false,
cursorStyles: ["pointer", "hovered", "locked"],
});
return (
<GlobalDispatchContext.Provider value={dispatch}>
<GlobalStateContext.Provider value={state}>
{children}
</GlobalStateContext.Provider>
</GlobalDispatchContext.Provider>
);
};
// Custom hook to use dispactch and state
export const useGlobalState = () => useContext(GlobalStateContext);
export const useGlobalDispatch = () => useContext(GlobalDispatchContext);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment