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:
- calls each sub-reducer;
- passes it only its corresponding slice of state;
- 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 userReducerAdvantages
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.nameSummary
| Function | What it does |
|---|---|
combineReducers(reducers) | Combines several reducers into one |
| Input | An object of the form { key: reducer } |
| Output | A single "root" reducer |
| Why it's needed | To split logic into independent state modules |
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.