Skip to content

Instantly share code, notes, and snippets.

@weivall
Created December 11, 2019 20:55
Show Gist options
  • Save weivall/3627339112a283bf0d21dd886ba5f4e0 to your computer and use it in GitHub Desktop.
Save weivall/3627339112a283bf0d21dd886ba5f4e0 to your computer and use it in GitHub Desktop.
React store
// store.js
import React, { createContext, useContext, useReducer } from 'react';
const StoreContext = createContext();
const initialState = {count: 0, message: ""};
const reducer = (state, action) => {
switch(action.type) {
case "increment":
return {
count: state.count + 1,
message: action.message
}
case "decrement":
return {
count: state.count - 1,
message: action.message
}
case "reset":
return {
count: 0,
message: action.message
}
default:
throw new Error(`Unhandled action type: ${action.type}`);
}
}
export const StoreProvider = ({ children }) => {
const [state, dispatch] = useReducer(reducer, initialState);
return (
<StoreContext.Provider value={{state, dispatch}}>
{children}
</StoreContext.Provider>
)
}
export const useStore = () => useContext(StoreContext);
// index.js
import React from "react";
import ReactDOM from "react-dom";
import { StoreProvider } from "./store";
import { ChildComponent } from "./childComponent";
function App() {
return (
<StoreProvider>
<ChildComponent/>
</StoreProvider>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment