Created
June 29, 2020 21:43
-
-
Save JeremyTheModernist/8d6b6e482ea3d82974f4bf8b2475e9ed to your computer and use it in GitHub Desktop.
Global React state with Reducer
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
import React, { createContext, useContext, useReducer } from "react"; | |
var StoreContext = createContext(); | |
var initialState = { | |
count: 0, | |
}; | |
var reducer = (state, action) => { | |
switch (action.type) { | |
case "increment": | |
return { | |
count: state.count + 1, | |
}; | |
case "decrement": | |
return { | |
count: state.count - 1, | |
}; | |
} | |
}; | |
export const StoreProvider = ({ children }) => { | |
var [state, dispatch] = useReducer(reducer, initialState); | |
return ( | |
<StoreContext.Provider value={[state, dispatch]}> | |
{children} | |
</StoreContext.Provider> | |
); | |
}; | |
export const useStore = () => useContext(StoreContext); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment