SaltyCrane Blog — Notes on JavaScript and web development

What does Redux's combineReducers do?

Redux uses a single root reducer function that accepts the current state (and an action) as input and returns a new state. Users of Redux may write the root reducer function in many different ways, but a recommended common practice is breaking up the state object into slices and using a separate sub reducer to operate on each slice of the state. Usually, Redux's helper utility, combineReducers is used to do this. combineReducers is a nice shortcut because it encourages the good practice of reducer composition, but the abstraction can prevent understanding the simplicity of Redux reducers.

The example below shows how a root reducer could be written without combineReducers:

Given a couple of reducers:

function apples(state, action) {
  // do stuff
  return state;
};

function bananas(state, action) {
  // do stuff
  return state;
};

This reducer created with combineReducers:

const rootReducer = combineReducers({ apples, bananas });

is equivalent to this reducer:

function rootReducer(state = {}, action) {
  return {
    apples: apples(state.apples, action),
    bananas: bananas(state.bananas, action),
  };
};

Usage without ES6 concise properties

The above example used ES6 concise properties, but combineReducers can also be used without concise properties. This reducer created with combineReducers:

const rootReducer = combineReducers({
  a: apples,
  b: bananas
});

is equivalent to this reducer:

function rootReducer(state = {}, action) {
  return {
    a: apples(state.a, action),
    b: bananas(state.b, action),
  };
};

Understanding how combineReducers works can be helpful in learning other ways reducers can be used.

References / see also