Skip to main content

What does combineReducers() do?

The problem combineReducers solves

In a real application, state is usually split into parts: for example, user, todos, cart, settings, and so on.

Each part is managed by its own reducer. But createStore() accepts only a single reducer.

The solution: combineReducers() combines all reducers into one "root" reducer.


Example

javascript
import { combineReducers, createStore } from 'redux' // Reducer for todos function todosReducer(state = [], action) { switch (action.type) { case 'ADD_TODO': return [...state, action.payload] default: return state } } // Reducer for the user function userReducer(state = { name: '' }, action) { switch (action.type) { case 'SET_USER': return { ...state, name: action.payload } default: return state } } // Combine the reducers const rootReducer = combineReducers({ todos: todosReducer, user: userReducer, }) // Create the store const store = createStore(rootReducer)

How it works internally

combineReducers() creates one shared reducer that:

  1. calls each sub-reducer;
  2. passes it only its corresponding slice of state;
  3. assembles everything back into a single state object.

So internally something like this happens:

javascript
function rootReducer(state = {}, action) { return { todos: todosReducer(state.todos, action), user: userReducer(state.user, action) } }

Visually

javascript
┌────────────────────────────┐ │ store │ {│ todos: [...],│ user: { name: 'Tim' }}└────────────────────────────┘ │ combineReducers ┌────────┴─────────┐ │ │ ▼ ▼ todosReducer userReducer

Advantages

Splits the code into independent modules (each reducer is responsible for its own "piece"). Simplifies testing and maintenance. Provides a structured state (state tree).


How to access state afterward

After combineReducers(), the state looks like this:

javascript
store.getState() // { todos: [...], user: { name: 'Tim' } }

Accordingly, to get the user's name:

javascript
const name = store.getState().user.name

Summary

FunctionWhat it does
combineReducers(reducers)Combines several reducers into one
InputAn object of the form { key: reducer }
OutputA single "root" reducer
Why it's neededTo split logic into independent state modules

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.