Last active
March 27, 2023 10:15
-
-
Save thchia/dd1bc8200fd8cff89cfa6c928983e5c4 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 }; | |
}, {}); | |
} |
@thchia well, to those who are not using Redux, like me, this is still useful. Thanks.
i cannot see the default values of each reducer on the rootReducer
@juanriglos each reducer should define its default state, not the rootReducer.
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
@viotti oops you are right! Anyway I think a lot of this has been superseded by the official hooks implementation in react-redux.
Instead of a
useStore
hook however (that has the same signature asuseReducer
), the recommended approach is to make use ofuseDispatch
anduseSelector
to access state and the dispatch function separately.