Be the first user to complete this post

  • 0
Add to List

combineReducers in reduxjs explained

In applications where you use redux for your data management, you often combine mutiple reducers into a root reducer. Then root reducer is used to create the store. Redux ships with a utility function called combineReducer, which simplifies this process. In this post, we will implement the combineReducer. For example, if we are creating a task manager application, then we will have a todoApp as a root reducer. We will also have todos and visibilityFilter, which manages the todos and visibilityFilter keys on the state object respectively. If we have to combine todos and visibilityFilter reducers then we can write the following function.

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

Then todoApp root reducer can be used to create the store as follows :
const { createStore } = Redux;
const store = createStore(todoApp);
The above pattern is so common that redux ships with the utility function called combineReducers, which allows us to write the following :
const { combineReducers } = Redux;
const todoApp = combineReducers({
  todos: todos,
  visibilityFilter: visibilityFilter
});

Convention: reducers are named after the state keys they manage allows us to write the following.
const { combineReducers } = Redux;
const todoApp = combineReducers({
  todos,
  visibilityFilter
});
Now, we will see how to implement combineReducers function.
  • It's a function which takes all the reducers as an argument.
  • It returns a function with the signature similar to the reducer(state = {}, action)
  • We will use Array.prototype.reduce to generate a single object
[wpgist id="dcb86657def2bd9390a170b8a4f17092" file="combineReducers.js"]



Also Read:

  1. Uncaught TypeError: Cannot read property 'toUpperCase' of undefined in React
  2. Use node in es6 syntax with babel transpiling
  3. Dynamic module loading with require
  4. Generating container components with connect utility in react redux app