Show Buttons
Share On Facebook
Share On Twitter
Share On Google Plus
Share On Linkdin
Share On Reddit
Share On Stumbleupon
Contact us
Hide Buttons

combineReducers in reduxjs explained

In appli­ca­tions where you use redux for your data man­age­ment, you often com­bine muti­ple reduc­ers into a root reducer. Then root reducer is used to cre­ate the store. Redux ships with a util­ity func­tion called combineReducer, which sim­pli­fies this process. In this post, we will imple­ment the combineReducer.

For exam­ple, if we are cre­at­ing a task man­ager appli­ca­tion, then we will have a todoApp as a root reducer. We will also have todos and visibilityFilter, which man­ages the todos and visibilityFilter keys on the state object respectively.

If we have to com­bine todos and visibilityFilter reduc­ers then we can write the fol­low­ing function.

const todoApp = (state = {}, action) => {
  return {
    todos: todos(state.todos, action),
    visibilityFilter: visibilityFilter(state.visibilityFilter, action)
  };
};

Then todoApp root reducer can be used to cre­ate the store as follows :

const { createStore } = Redux;
const store = createStore(todoApp);

The above pat­tern is so com­mon that redux ships with the util­ity func­tion called combineReducers, which allows us to write the following :

const { combineReducers } = Redux;
const todoApp = combineReducers({
  todos: todos,
  visibilityFilter: visibilityFilter
});

Con­ven­tion: reduc­ers are named after the state keys they man­age allows us to write the following.

const { combineReducers } = Redux;
const todoApp = combineReducers({
  todos,
  visibilityFilter
});

Now, we will see how to imple­ment combineReducers function.

  • It’s a func­tion which takes all the reduc­ers as an argument.
  • It returns a func­tion with the sig­na­ture sim­i­lar to the reducer(state = {}, action)
  • We will use Array.prototype.reduce to gen­er­ate a sin­gle object

You may also like...