Showing posts with label createStore. Show all posts
Showing posts with label createStore. Show all posts

Friday, August 14, 2020

Redux Overview

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.

store in Redux

In Redux store is the state object which holds the Application state. The current state can be accessed using store.getState() and any changes to the state can be performed by dispatching an action to the reducer.

In the previous posts, we saw how to create the store object using createStore and use it to initialize the application. Redux store also allows us to subscribe to events that update the store object. This can be useful to debug changes to the redux store.

In the createStore code of the previous example we will add a subscription to display changes to the state to the console as follows.

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.

Reducers in Redux

Reducers are pure functions in redux which are used to modify the state object of the Application. All Actions are handled in reducers they will get the payload from the action and modify the state as defined.

Reducers take the previous state of the app and return a new state based on the action passed to it.
As pure functions, they do not change the data in the object passed to them or perform any side effect in the application. Given the same object, they should always produce the same result. Actions performed on the state always return a new state. Thus, the state is very easy and predictable.

In the previous post, we was a SET_NAME action below is the reducer which handles the SET_NAME action.