Composition
- React course
- Intermediate
- Lesson 15/80
- 4 min
Learn to combine multiple reducers.
Composition
For large state, a single reducer gets bloated. The fix: reducer composition. Split the state into parts, write a reducer for each part, then combine them in a root reducer.
For example, userReducer and cartReducer are written separately. The root reducer: function rootReducer(state, action) { return { '{ user: userReducer(state.user, action), cart: cartReducer(state.cart, action) }' }; }.
This pattern comes from Redux and has become standard in big apps. Each sub-reducer can be tested independently; maintenance is easier. The same method applies with useReducer.
Nested state
State is usually nested: { '{ user: {...}, cart: {...} }' }. With composition, each sub-field has its own reducer. The root reducer just dispatches.
Each sub-reducer sees only its field: userReducer(state.user, action). This keeps reducers small and focused. Testing is easy one by one.
This approach also makes adding a new field (like theme) easy later. You write a new themeReducer and add it to the root; others stay the same.
Practice Write rootReducer
Complete the skeleton. Write a rootReducer function. Take (state, action). Return the object { '{ user: userReducer(state.user, action), cart: cartReducer(state.cart, action) }' }. Export it.
Starter code
// Write the rootReducer function hereSample solution
function rootReducer(state, action) {
return {
user: userReducer(state.user, action),
cart: cartReducer(state.cart, action),
};
}
export default rootReducer;Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 When is composition used?
- In useEffect
- For small state
- In CSS
- For big state Correct answer
Explanation: Composition is used for big state.
2 Root reducer
The root reducer combines the sub-reducers in ____.
The root reducer combines the sub-reducers in bir nesne.
Explanation: Root reducer returns an object.
3 Match the composition steps
| Term | Meaning |
|---|---|
userReducer |
user |
cartReducer |
cart |
rootReducer |
combines |
sub-reducer |
small |