Skip to content

Instantly share code, notes, and snippets.

@condratf
Forked from thchia/combineUseReducers.js
Created May 28, 2020 17:36
Show Gist options
  • Save condratf/c3c941b615e591f5dce925e2a518c4ad to your computer and use it in GitHub Desktop.
Save condratf/c3c941b615e591f5dce925e2a518c4ad to your computer and use it in GitHub Desktop.
Combining the useReducers Hook
// Main
function combineReducers(reducerDict) {
const _initialState = getInitialState(reducerDict);
return function(state = _initialState, action) {
return Object.keys(reducerDict).reduce((acc, curr) => {
let slice = reducerDict[curr](state[curr], action);
return { ...acc, [curr]: slice };
}, state);
};
}
function useStore(rootReducer, state) {
const initialState = state || rootReducer(undefined, { type: undefined });
return useReducer(rootReducer, initialState);
}
// Usage
function reducerA(state, action) {
// ...
}
function reducerB(state, action) {
// ...
}
function reducerC(state, action) {
// ...
}
const rootReducer = {
group1: combineReducers({ a: reducerA, b: reducerB }),
group2: reducerC
}
// Use this in a Context Provider and get access to state and dispatch
// anywhere by using useContext.
const [state, dispatch] = useStore(rootReducer) // optional state object as second arg
// Helpers
function getInitialState(reducerDict) {
return Object.keys(reducerDict).reduce((acc, curr) => {
const slice = reducerDict[curr](undefined, { type: undefined });
return { ...acc, [curr]: slice };
}, {});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment