Friday, August 14, 2020

combineReducers in Redux

In the previous post, we saw about Redux reducers, how to create them, and bind it to the store when the Application gets initialized. This approach of creating and initializing a single reducer works well for small Applications.

When the application grows it might be difficult to hold the state of all the components in a single file, as it will grow too big making it difficult to maintain, we would like to split the reducer code across different reducer files for maintainability. To achieve this redux provides a utility combineReducers(), this can take multiple reducers and merge them into a single reducer before assigning it to the store.

Let us extend the previous example, add multiple reducers and use combineReducers() to merge them into a single reducer and assign it to the state as follows.
import { combineReducers, createStore } from 'redux';
import { homeReducer } from './homeReducer';
import { listReducer } from './listReducer';

const rootReducer = combineReducers({
    homeReducer,
    listReducer
  })

export const store = createStore(rootReducer);

When using combineReducer to merge different reducers files, we need to use the access hierarchy of the reducers to access specific properties of reducer as follows.

function mapStateToProps(state) {
  return {
    name: state.homeReducer.name,
    greeting: state.homeReducer.greeting
  };
}

Notice that we are using state.homeReducer.name to access the name property in the homeReducer, if we don’t use combineReducer and just use a single reducer then we can directly access the name property like state.name

This also helps us avoid conflicts, so that we can have the same property name in more than one reducer. 


Search Flipkart Products:
Flipkart.com

No comments: