Skip to content

Instantly share code, notes, and snippets.

@MeetMartin
Created July 30, 2021 02:40
Show Gist options
  • Save MeetMartin/b96bb51763280165ce924631dfb216e5 to your computer and use it in GitHub Desktop.
Save MeetMartin/b96bb51763280165ce924631dfb216e5 to your computer and use it in GitHub Desktop.
// /src/store/StoreContext.js
import React, { createContext, useReducer, useEffect } from 'react';
import { reducer, initialState } from './reducers';
import { useActions } from './actions';
import { applyMiddleware } from './middleware';
const StoreContext = createContext(initialState);
const StoreProvider = ({ children }) => {
// Set up reducer with useReducer and our defined reducer, initialState from reducers.js
const [state, dispatch] = useReducer(reducer, initialState);
// Attach middleware to capture every dispatch
const enhancedDispatch = applyMiddleware(state)(dispatch);
// Create an object of all our actions, handling special cases where a simple dispatch is too primitive
const actions = useActions(state, enhancedDispatch);
// Log new state
useEffect( () => {
console.debug('[StoreProvider state] state updated', state);;
}, [state]);
return (
<StoreContext.Provider value={{ state, enhancedDispatch, actions }}>
{children}
</StoreContext.Provider>
);
};
export { StoreContext, StoreProvider };
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment