Skip to content

Instantly share code, notes, and snippets.

@Justkant
Last active November 7, 2018 22:41
Show Gist options
  • Save Justkant/a3287b89682a215a8b8b67c50f690b11 to your computer and use it in GitHub Desktop.
Save Justkant/a3287b89682a215a8b8b67c50f690b11 to your computer and use it in GitHub Desktop.
redux like concept with react 16 context and react 16.7 beta hooks (https://codesandbox.io/s/jvklvmp8l9)
import React from "react";
import Provider from "./Provider";
import Counter from "./Counter";
const App = ({ reducer, initialState }) => {
return (
<Provider reducer={reducer} initialState={initialState}>
<Counter />
</Provider>
);
};
export default App;
import { createContext } from "react";
export const StoreContext = createContext({});
import React, { useContext } from "react";
import { StoreContext } from "./context";
const Counter = () => {
const [state, dispatch] = useContext(StoreContext);
return (
<>
Count: {state.count}
<button onClick={() => dispatch({ type: "reset" })}>Reset</button>
<button onClick={() => dispatch({ type: "increment" })}>+</button>
<button onClick={() => dispatch({ type: "decrement" })}>-</button>
</>
);
};
export default Counter;
import React from "react";
import { render } from "react-dom";
import App from "./App";
const initialState = { count: 0 };
function reducer(state, action) {
switch (action.type) {
case "reset":
return initialState;
case "increment":
return { count: state.count + 1 };
case "decrement":
return { count: state.count - 1 };
default:
return state;
}
}
render(
<App reducer={reducer} initialState={initialState} />,
document.getElementById("root")
);
import React, { useReducer } from "react";
import { StoreContext } from "./context";
const Provider = ({ reducer, initialState, children }) => {
const store = useReducer(reducer, initialState);
return (
<StoreContext.Provider value={store}>
{children}
</StoreContext.Provider>
);
};
export default Provider;
@Justkant
Copy link
Author

Justkant commented Nov 7, 2018

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment