Created
February 29, 2020 08:15
-
-
Save GeekSnail/ba8132ee7c23a30c12757f8f27baed93 to your computer and use it in GitHub Desktop.
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, useContext, useReducer } from "react"; | |
export const StateContext = createContext(); | |
export const StateProvider = ({ reducer, initialState, children }) => ( | |
<StateContext.Provider value={useReducer(reducer, initialState)}> | |
{children} | |
</StateContext.Provider> | |
); | |
export const useStore = () => useContext(StateContext); | |
//-----------------------------------------------------// | |
const store = { | |
initialState: { | |
count: 0 | |
}, | |
reducer: (state, action) => { | |
switch (action.type) { | |
case "increment": | |
return { ...state, count: state.count + 1 }; | |
case "decrement": | |
return { ...state, count: state.count - 1 }; | |
default: | |
return state; | |
} | |
} | |
}; | |
export default function App() { | |
return ( | |
<StateProvider {...store}> | |
<Counter /> | |
</StateProvider> | |
); | |
} | |
export function Counter() { | |
const [state, dispatch] = useStore(); | |
console.log(state, dispatch); | |
return ( | |
<div> | |
{state.count} | |
<button onClick={e => dispatch({ type: "increment" })}>+</button> | |
<button onClick={e => dispatch({ type: "decrement" })}>-</button> | |
</div> | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment