Skip to content

Instantly share code, notes, and snippets.

@thchia
Last active March 27, 2023 10:15
Show Gist options
  • Star 23 You must be signed in to star a gist
  • Fork 7 You must be signed in to fork a gist
  • Save thchia/dd1bc8200fd8cff89cfa6c928983e5c4 to your computer and use it in GitHub Desktop.
Save thchia/dd1bc8200fd8cff89cfa6c928983e5c4 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 };
}, {});
}
@thchia
Copy link
Author

thchia commented Apr 26, 2020

@juanriglos each reducer should define its default state, not the rootReducer.

@juanriglos
Copy link

Yes i am sure about that, but tried to access a reducer state in the store, before made any action, and second the perfomance it is not the best option, it will bring the hole store always

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