Showing posts with label combineReducers. Show all posts
Showing posts with label combineReducers. Show all posts

Friday, August 14, 2020

Adding Redux to a React App

In the previous few posts we saw about Action, Reducer and Store concepts about Redux. In this post we shall see on how to put all of these together to add a Redux store to a React application.

In this sample we will create a simple React application, with a textbox where the user can type his name and a button on click of which a Welcome message is displayed with the name. The onChange event of the textbox and the onClick event of the button will dispatch actions to update the corresponding property in redux store.

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.