Last active
June 20, 2024 10:09
-
-
Save chengsokdara/1535c912fa18fbb882cb9d74f7760f85 to your computer and use it in GitHub Desktop.
React global state in 15 lines of code.
This file contains hidden or 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
| // Author: Sokdara Cheng | |
| // Contact me for web or mobile app development using React or React Native | |
| // https://chengsokdara.github.io | |
| import React, { createContext, useContext, useReducer } from "react"; | |
| import initialState from "./initialState"; // object of initial states | |
| import reducer from "./reducer"; // https://reactjs.org/docs/hooks-reference.html#usereducer | |
| const Store = createContext({ | |
| dispatch: () => null, | |
| state: initialState, | |
| }); | |
| const StoreProvider = ({ children }) => { | |
| const [state, dispatch] = useReducer(reducer, initialState); | |
| return ( | |
| <Store.Provider value={{ dispatch, state }}>{children}</Store.Provider> | |
| ); | |
| }; | |
| export const useStore = () => useContext(Store); | |
| export default StoreProvider; | |
| /* | |
| * How To Use: | |
| * - wrap root App component with StoreProvider | |
| * <StoreProvider><App><StoreProvider> | |
| * | |
| * - call useStore to get state and dispatch | |
| * const { state, dispatch } = useStore() | |
| * | |
| * - change state by passing action to dispatch | |
| * dispatch({ type: 'TEST_ACTION', payload: { test: 'new value' } }) | |
| * | |
| * | |
| * // initialState.js | |
| * export default { | |
| * test: "test", | |
| * }; | |
| * | |
| * // reducer.js | |
| * export default (state, action) => { | |
| * switch (action.type) { | |
| * case "TEST_ACTION": | |
| * return { | |
| * ...state, | |
| * ...action.payload, | |
| * }; | |
| * default: | |
| * return state; | |
| * } | |
| * }; | |
| */ |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@AshleyAitken