JS Built-ins
redux-legacycombineReducersintermediate

Combine Reducers (Manual)

πŸ“– Usage Example
const rootReducer = combineReducers({
  counter: counterReducer,
  user: userReducer,
})

store.getState()
// β†’ { counter: 0, user: { name: '' } }

combineReducers delegates each slice of state to a dedicated reducer, keeping each reducer focused and small.

Combine Reducers (Manual)

combineReducers is one of Redux's most important utilities. It takes an object of reducer functions and returns a single root reducer that calls each one for its slice of state:

function combineReducers(reducers) {
  return function(state = {}, action) {
    // call each reducer with its slice of state
  }
}

The resulting state object has the same keys as the reducers object, each key holding the result of the corresponding sub-reducer.

Challenge: Implement combineReducers(reducers) from scratch.

πŸ’‘ Hints (2)
  • β€’ Iterate over `Object.keys(reducers)` and call each reducer with `state[key]` and the action.
  • β€’ If `state` is undefined (first call), initialise it to `{}` so each sub-reducer receives `undefined` and can use its own default.