Be the first user to complete this post
|
Add to List |
combineReducers in reduxjs explained
In applications where you use redux for your data management, you often combine mutiple reducers into a root reducer. Then root reducer is used to create the store. Redux ships with a utility function called combineReducer
, which simplifies this process. In this post, we will implement the combineReducer
.
For example, if we are creating a task manager application, then we will have a todoApp
as a root reducer. We will also have todos
and visibilityFilter
, which manages the todos
and visibilityFilter
keys on the state object respectively.
If we have to combine todos
and visibilityFilter
reducers then we can write the following function.
const todoApp = (state = {}, action) => {
return {
todos: todos(state.todos, action),
visibilityFilter: visibilityFilter(state.visibilityFilter, action)
};
};
Then todoApp
root reducer can be used to create the store as follows :
const { createStore } = Redux;
const store = createStore(todoApp);
The above pattern is so common that redux ships with the utility function called combineReducers
, which allows us to write the following :
const { combineReducers } = Redux;
const todoApp = combineReducers({
todos: todos,
visibilityFilter: visibilityFilter
});
Convention: reducers are named after the state keys they manage allows us to write the following.
const { combineReducers } = Redux;
const todoApp = combineReducers({
todos,
visibilityFilter
});
Now, we will see how to implement combineReducers
function.
- It's a function which takes all the reducers as an argument.
- It returns a function with the signature similar to the reducer(state = {}, action)
- We will use
Array.prototype.reduce
to generate a single object
Also Read:
- Pure vs Impure functions
- Passing the store down implicitly via context in a react redux app
- Disable eslint no-unused-vars warning on global functions
- Create Reducer for Redux Applications