Last active
December 27, 2021 08:34
-
-
Save LishuGupta652/1c66ace186f991b1e2328d69d549f5bf to your computer and use it in GitHub Desktop.
Global Reducer + context
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, 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