Default Values

Learn about the default value requirement in reducers.

One of the requirements of combineReducers() is for each reducer to define a default value for its substate. When using this approach, the default structure of the state tree is built dynamically by the reducers. This guarantees that changes to the tree require changes only to the applicable reducers and do not affect the rest of the tree.

This is possible because Redux dispatches a special action called @@redux/INIT when the store is created. Each reducer receives that action together with the undefined initial state, which gets replaced by the default parameter defined inside the reducer.

Because our switch statements in the previous example do not process this special action type and simply return the state, the reducers automatically populate the initial state of the store.


const recipesReducer = (recipes, action) => {
  switch (action.type) {
    case ADD_RECIPE:
      return recipes.concat(action.payload);
    ...
  }
}

To support this, each of the sub-reducers must define a default value for its first argument to use if none is provided:

const initialState = [];

const recipesReducer = (recipes = initialState, action) => {
  switch (action.type) {
    case ADD_RECIPE:
      return recipes.concat(action.payload);
    ...
  }
}

Get hands-on with 1200+ tech skills courses.