Skip to content

Instantly share code, notes, and snippets.

@GeekSnail
Created February 29, 2020 08:15
Show Gist options
  • Save GeekSnail/ba8132ee7c23a30c12757f8f27baed93 to your computer and use it in GitHub Desktop.
Save GeekSnail/ba8132ee7c23a30c12757f8f27baed93 to your computer and use it in GitHub Desktop.
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