Combining Reducers

Learn how to combine reducers.

The technique of reducer combination is so convenient and broadly used that Redux provides the combineReducers() function to facilitate it. This helper function does exactly what rootReducer() did in our earlier example, with some additions and validations:

import { combineReducers } from 'redux';
import recipesReducer from 'reducers/recipes';
import ingredientsReducer from 'reducers/ingredients';
import ui from 'reducers/ui';

const rootReducer = combineReducers({
  recipes: recipesReducer,
  ingredients: ingredientsReducer
});

export const store = createStore(rootReducer);

We can make this code even simpler by using ES2015’s property shorthand feature:

import { combineReducers } from 'redux';
import recipes from 'reducers/recipes';
import ingredients from 'reducers/ingredients';
import ui from 'reducers/ui';

export default combineReducers({
  recipes,
  ingredients,
  ui
});

In this example, we provided combineReducers() with a configuration object holding keys named recipes, ingredients, and ui. The ES2015 syntax we used automatically assigned the value of each key to be the corresponding reducer.

Note: The combineReducers() is not limited only to the root reducer. As our state grows in size and depth, nested reducers will combine reducers for substate calculations. Using nested combineReducers() calls and other combination methods is a common practice in larger projects.

Get hands-on with 1400+ tech skills courses.