-
-
Save condratf/c3c941b615e591f5dce925e2a518c4ad to your computer and use it in GitHub Desktop.
Combining the useReducers Hook
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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