Search

What is React Redux?

React is a JavaScript library for building user interfaces. One of the most popular UI libraries in use today, React is opensource and is maintained by Facebook. React has the best community support, with millions of developers who take part in discussions on best practices, React architecture, and the way forward with React.You can read more about React here.In this blog you are going to learn about React Redux. We can use it along with React for state management within the application.Prerequisites:This blog expects you to have good knowledge of JavaScript.You should have basic understanding of React, React Hooks and Components in React.Please ensure that the latest versions of npm and node are installed in your machine.To get started with React Redux, let’s first see what Redux is:What is Redux?Redux is a predictable state container for JavaScript apps, which means that Redux is predictable and it stores the state of your application. Redux will store and manage the application state.Redux itself is a standalone library that can be used with any UI layer or framework. Along with React, Redux can be used with many other JavaScript libraries and frameworks such as Angular, Vue and even with Vanilla JavaScript.You can read more about Redux here.When we are building a large-scale application, there is a need for a state management tool to avoid prop drilling all through the component. Redux is the most popular and widely used state management tool today.Note: Redux does what context api does in React. However, Redux was introduced before context api was introduced, and it continues to be the most popular state management library.In the next part of this article, you will learn to use Redux and in later parts you can learn how to integrate it with your React application.Learn Redux:Here you will understand the essential core concepts of Redux before learning how to use it with React.Start with creating an empty folder with the name Redux-Learnings in your desired location and open the folder in your favourite editor. VScode is preferred.Initially your project folder looks like this when it is opened in VScode:It should be empty. Let’s setup our project first.Now, let’s initialize a package.json file to store all our dependencies to learn Redux.Open integrated terminal for vscode and navigate to the project location.Next, run the below command in our terminal to initialize package.json in our project.Command: npm init –yesThere should be a package.json file inside the project as shown below.The next step is to install redux as a dependency for our project. Run the below command in the terminal to add redux as a dependency.Command: npm install reduxIf you check package.json file, you can see redux listed under the dependencies as shown below:Now create a file with the name index.js at the root level of the project and add a simple console statement to see the output on the terminal as shown below.Now, run the below command to run the index.js file.Command: node indexIt has to print the console statement to the terminal as shown below.Let’s start learning some theory behind Redux.Redux has 3 main components:StoreAction  ReducerWe will explain these components with the help of a real-world scenario.Imagine there is a restaurant, and you want to buy a meal. You will go to the restaurant and tell the retailer that you want to BUY a meal. The retailer takes out the meal from the bunch of meals with him, and gives it to you. You will then pay the money for the meal and get the receipt for the purchase. The receipt for the purchase is the proof that the number of meals has been decreased by one.Let’s see the 3 components in relation to the above scenario:Store: The store holds all the states of the application. This is similar to the restaurant holding all the meals.  Action: The Action here is to BUY_A_MEAL which describes what has happened. In this case you have bought a meal. The action describes changes in the state of the application.  Reducer: Reducers are similar to the retailer. They connect the store to the actions. In this case the retailer is decreasing the number of meals the restaurant (store) has. Reducers update the store according to the action.To put the 3 components of Redux into code, it’s important to learn the 3 main principles of Redux:The state of the whole application is stored in a single main object in the store. This means state is a single JavaScript object and lies inside the store. In our example, all the meals of the restaurant are to be represented in a single object. For example: { numberOfMeals: 10}The only way to change the state is to emit an Action. Emitting an action is the way of letting the Redux know what has happened. It’s an object describing what has happened. In our example BUY_A_MEAL is the action which is describing the action of buying a meal. You are NOT ALLOWED to update the state directly, but you always need an action to update the state.  Actions have types. For example: {type: “BUY_A_MEAL”}To specify how state changes based on actions, we use Reducers. A Reducer is a function that take initial state and action as inputs, and returns new state based on the type the action has. An example of a reducer for the above example is shown below. It decreases the number of meals in the restaurant (store).const reducer = (state, action) => {   switch(action.type) {     case BUY_A_MEAL:        return {         numberOfMeals: state.numberOfMeals-1       }   } }Now let’s start coding our Redux app.As you have seen already, the 3 main components of redux are to be implemented in code. Let’s start with Actions.Creating Action:As you know that Actions are plain JavaScript objects and have ‘type’ property, which indicates the type of the actions being performed. You are not restricted to just having a type property;  instead, you can have additional properties as well.Also, in Redux we have action creator. As the name suggests, an action creator is a function which simply creates an action.Let’s go back to the project we have setup earlier and start coding Actions.  The Action Type and the Action Creator for our restaurant example can be written as shown below.Here BUY_A_MEAL is an action type and function buyMeal is an action creator, which returns an action which has type and the description in it.Creating Reducer:As we already know, a reducer is a function which takes in initial State and action, and returns a new state based on the type of action.The reducer can be created as shown below:Here the reducer is taking in the initial state and the action and returns the new state in the switch statement, where we compare the type in the case block and return the new state object.…state means that we are creating a copy of the state object and we are changing only the required properties.However, it's important to keep in mind that in redux we cannot change the state. Instead a new state is created with the changed properties and that is stored inside the Store.Creating Store:Before creating a store, its required to know the characteristics of Store:  Store holds the state of the application. Store provides a method called dispatch which allows updates to the application state. Dispatch method accepts an action as its parameter. Store allows components to access the state via getState() method. Registers listeners via subscribe method. That is the listener is called whenever the state is changed inside the store. Listener is a function which is passed to the subscribe method to call whenever the state changes. Unregister the listeners using the function returned by the subscribe method.Now let’s implement all the above in the code. If you see, we already have the state object by the name initialState in our code. Let’s create a store to hold our state using the redux package we installed earlier.As shown above, import Redux package using the required syntax. We need to make use of createStore method in Redux to create a store.Create a store by calling createStore method we pulled out from redux.createStore takes reducer as the parameter which has the application state.The store we created has the getState method which gives us the state of the application. To prove this, let’s add the console statement as shown below.If you run the file using node index command, you can see the console statement is printing the initial state to the console.  Now let’s quickly implement subscribe and dispatch methods as shown below.As mentioned earlier subscribe method takes a function as an argument. Here it’s a simple console statement which prints the state.  dispatch method takes in the action creator as an argument. I have just called it more times to trigger the state transitions more times.If you run the index file, you can see that the subscribe method is calling the listener function for every state change, and printing the new state as you can see above.  Now let’s unsubscribe to the listeners by calling the method returned by the subscribe method as shown below.Capture the unsubscribe method returned by the subscribe method, and call it in the middle to prove that we are unsubscribed to the state changes.If you can see above, listener has been called only 3 times for the 4 dispatch calls we made, as we unsubscribed before the 4th dispatch call.What is happening when we call dispatch method?When we call the dispatch method it dispatches an action buyMeal to the reducer which is returning the action which has a type BUY_A_MEAL. Now the reducer looks at the action type and compares with the case mentioned and returns the new state. As the state changes and the new state gets created in the store, the listener gets called and prints the new state to the console.This is the flow of redux. Going forward, do make sure that you understand and remember this flow.What if we have multiple actions?Let’s take the restaurant example again and say that we have snacks along with meals and we have different retailers(reducers) for each of these.  So, first step first, you need to update the initialState object to add the number of snacks and action type to buy a snack as shown below.Now let’s add an action creator to buy a snack (buySnack method).And also, a reducer case to handle buying a snack caseAnd also add some dispatch methods to dispatch buySnack action.Now if you run the index.js file and see the terminal output when buyMeal is dispatched, only the number of meals decreases, and when buySnack is dispatched only the number of snacks decreases.This method of using a single reducer works in this case. However, in a large-scale application, it gets hard to maintain and debug, also hard to keep track of the work flow.So, in many cases developers tend to create multiple reducers.  Create multiple reducers:For this you need to split the initial state of the application within index.js as shown belowHere, initialState object has been split into 2 state objects; one to store the number of Meals(initialMealState) and one to store the number of Snacks(initialSnackState).Similarly, we will split the reducer into 2 parts.Reducer related to Meals.Here, we have made mealReducer to handle actions related to Meals.Reducer related to Snacks.Here, we have made snackReducer to handle actions related to Snacks.If you observe by splitting the state and reducer, we are maintaining the centralized state and reducer functions for each component or feature in our application. By doing this it's always easy to maintain the code and to keep track of the workflow too.But if you look at the createStore method there is reducer passed in as an argument but now it no more exists. So, we need to combine the reducers before we pass it to createStore method.Combining Reducers:Combining reducers is very simple, and we can do this by using the combine reducers function which redux package offers.Extract combineReducers function from redux package as shown below:Now we need to combine all the reducers we have using the method we extracted above.The combineReducers function takes an object as a parameter which has all the reducers we have created as a key value pairs, and its generally called as rootReducer.We have to pass that rootReducer as an argument to the createStore method as shown in the above image.  Now if you run the file using node index you will see something like this inside the terminal.The meal and snack in the state object corresponds to the meal and snack keys we specified while combining the reducers.Now we have centralized state and reducers for each of our meals and snacks. We can add more actions to the existing reducers or even add new reducers. Also, it’s easy to maintain the code.This is the flow of the redux. We dispatch an action which has a type property to the reducer, and the reducer—based on the action type— updates the store accordingly.In real time applications, the actions are not synchronous as we have learnt above. We may have asynchronous actions, or we may want to add additional functionality to our redux workflow. For all of this we need to use middlewares.Middlewares:  Middlewares are the suggested way to extend redux functionality. Middlewares provide third party extension between dispatching an action and the moment the action reaches the reducer.Middlewares are normally used for logging, crash reporting or to perform some async tasks.  For example, we will now see how to add a middleware by using redux-logger middleware.  Read more about redux logger here.To install redux logger, go to vs code and run the following command in the terminal.Command: npm install redux-loggerNow if you go to the above-mentioned link for redux logger, you will find the code we write now.  We need to require the redux logger we just installed and create a logger as shown below.Now to apply this middleware, Redux has a function built into it which is called applyMiddleware.Extract applyMiddleware function from redux as shown below.Now pass the applyMiddleware as a second parameter to the createStore function as shown below.applyMiddleWare takes all the middlewares we have as arguments. In our case, it is logger.To see the middleware in action, remove the console.log statement inside the subscribe method of store and run the file using node index. You should see the outputs of the logger in the terminal as shown below.As mentioned above the actions used in the above example are synchronous actions but in real time applications the actions will be asynchronous.  As soon as we dispatch an action the state is updated in the above example. But in real time apps we may need to do an API call before we update the state. These types of actions are called asynchronous actions or async actions.Now let’s see how async actions are handled.Handling async actions:For this, let’s make an API call to fetch some users.So, let’s go to the same project we have been working with, for the above example, and create a new file asyncActions.js and work in this file.To implement redux, we need 3 things as we have learnt:StateActionsReducersLet’s look at each one of them.State:The state object looks like this:The loading key in the state object is set to false initially, and it is used to show a spinner when we are making an API call.The users key in the state object is initially set to an empty array, as we get an array of users after making the API call.The error key in the state object is initially set to an empty string as if the API call fails, we get the error string and we store the error message in this error key.Actions:  The action types and the action creators can be written as shown below.The fetchUsersLoading action creator can be used when the API call is in progress. So, this returns action type FETCH_USERS_LOADING.The fetchUsersSuccess action creator can be used when the API call is successful. We get an array of users as an argument for this function which returns the users array as a payload along with action type FETCH_USERS_SUCCESS.The fetchUsersFail action creator can be used when the API call fails, and we get an error message string as an argument for this function which returns the error message as a payload along with the action type FETCH_USERS_FAIL.Reducer:The reducer for the given scenario can be written as shown below.As mentioned already, FETCH_USERS_LOADING denotes that the API call is going on so loading should be set to true.FETCH_USERS_SUCCESS denotes that the API call is done and was successful. We can set loading to false again and users to action.payload as we are sending users inside payload in the action creator.FETCH_USERS_FAIL denotes that the API call is done and failed. We set loading to false again and error to action.payload as we are sending the error message inside payload in the action creator. Users is sent to an empty array as we will not get any users from the API.Now the last step remaining is to create the redux store.Create the store in the same way as the previous example.Now let’s see how to make an api call and actually handle async actions.To make an api call we use axios. You can read more about axios here.To define async action creators we use redux-thunk. It is a middleware that must be used in the same way that we used logger in the previous example.Read more about redux-thunk here.We need to install both the packages in order to use them. For that, open the terminal and run the following command.Command: npm install axios redux-thunkLet’s apply redux-thunk middleware as shown below. By requiring the redux-thunk and making use of applyMiddleWare in the same way as the previous example, we get:Now let’s write our async action creator which dispatches action creators which we have created earlier.We will make use of this API.First import axios as shown below.Next, make an API call for the above-mentioned end point using axios in our async action creator as shown below.Here fetchUsers is our async action creator and as we are using redux-thunk we can define async action creators. Redux-thunk allows us to return a function which has access to dispatch method through the arguments so that we can dispatch actions.We dispatch fetchUsersLoading initially as we are making an api call.Once the api call is successful we dispatch fetchUsersSuccess along with users as argument.If the API call fails, we dispatch fetchUsersFail along with the error message.  This is our async action creator which dispatches the necessary synchronous actions whenever required.Now write a subscribe method as shown in the above image and dispatch fetchUsers at the last.In the terminal, to run the file use the below command.Command: node asyncActions.jsYou can see the list of users in the terminal as shown below.Redux-thunk is widely used middleware to handle side effects such as API calls and other async tasks. It's important that you should learn about this package.And that’s it! You have completed learning about Redux concepts.Next, we move on to learning how to integrate Redux with your React application.  Before we start learning to integrate redux with react, let’s take a look at what react redux is.What is React Redux?React is a UI library whereas Redux is a state management library. They both work independently. We cannot use Redux directly in a react application, so we use React Redux to bind Redux in our React applications.React Redux is the official Redux UI binding library for React. If you are using Redux and React together, you should also use React Redux to bind these two libraries.This means if we want to use React and Redux together, we also need to use React Redux to bind them together.  For more information on React Redux, check this link.Installation:To directly create a redux app, run the following command inside the terminal.Command: npx create-react-app my-app --template reduxNavigate into the application using cd command and start making changes to the application.To integrate redux into an existing react project, run the following command inside the react project.Command: npm install redux react-reduxThis installs redux and react-redux packages to the React application and we can start integrating redux with react.We are going to follow the second method as we are going to integrate redux with the existing react application.Let’s try rebuilding the above example with a UI.We will start with the setup as shown below. This has been created using create-react-app and has been changed according to our needs.Folder structure:App.js:App.js has only one component called MealContainer.MealContainer.js:Now if you run the app using the npm start command you will see the similar UI in the browser.Now, let’s start with integrating redux with our react application.As mentioned above, install redux and redux-thunk by running the below command.Command: npm install redux react-reduxAfter the installation, create a new folder inside src with the name redux. All our redux logic goes into this folder. Now inside this, I would like to create folders with the feature names as all the logic related to a particular feature can be kept organized in a single place. As we have only one feature by the name meals, create a folder with the name meals and 2 files with the names mealActions.js and mealTypes.js to create the actions and action types for this particular feature as shown below.Inside the mealTypes.js export the action type as shown below.Note: export keyword is used so that we are able to use the particular function or object in other files by importing them using import key word.Create an action creator to buy a meal as we have learnt in the previous example.Now let’s create reducer for our meals feature. For this, create a new file with the name mealReducer.js inside the same folder and create reducer for the meals feature.Now let’s create the redux store. For this, create a file with the name store.js inside redux folder as store is common for all the features. Next, create a store as we have already learnt, and export it as the default.Now that we have set up our redux for the application, how does our application get access to the store? Well, for that we need to go to the react-redux package we installed; this is where react-redux makes its first appearance. We need to go to Provider which react-redux offers in order to make our app know about the store.Go to the app.js file and import Provider from react-redux, and wrap the whole app with this provider passing store as a prop to it.Now what remains is to connect redux to our components, dispatch an action and update the store from the components.Connecting redux to the components:As a first step, write a couple of functions mapStateToProps and mapDispatchToProps as shown below.mapStateToProps is a function that you would use to provide the store data to the component as prop. Whereas mapDispatchToProps is something that you will use to provide the action creators as props to the component.Read more about the 2 functions here.We import buyMeal action from the action file to use in mapDispatchToProps.Now to connect both the functions to the component, we need to import connect which react-redux offers us as shown below.Now using that, we connect the state and actions to the component as shown below.mapStateToProps and mapDispatchToProps are passed as arguments to the connect function.Now we can access the numOfMeals using the props object and show that in the UI.The numOfMeals upon the props pertains to the key returned by the object in the mapStateToProps.If you save and check the UI, you can see the number of meals displayed.Now let’s dispatch our buyMeals action. This is available on the props object, as we have used mapDispatchToProps. Upon the click of the button, we execute the function which dispatches our action as shown below.Now if you click the button in the UI, the meals should decrease by 1.Now, let’s integrate logic for the snacks as well.  Add SnackContainer.js file similar to mealContainer and add it in the App.js file as shown below.In the redux folder, add a new folder for snacks feature and add the necessary files in the same manner as the meals folder.snackTypes.jssnackActions.jsNext, write the reducer in the snackReducer.jsAs we have 2 reducers, we need to combine reducers as we have learnt previously, and pass the rootReducer to the store.Due to this change, the application will break as we have changed the structure of the state in the store. So, we need to make some changes in mealContainer as shown below.Let’s connect the state to the snackContainer component in the same way that we have done in the mealContainer component, as shown below.If you check the UI, you will be able to see the number of snacks displayed as shown below.If we click on the Buy Snacks button, that should decrease the number of snacks by 1.And that’s it! We have implemented React-Redux along with the React UI.Let’s see how to manage Async actions in UI.If you see, we have rewritten the same code we have used to learn Redux.Let’s implement the same API call example we have learnt above in React. We will consider that these are the users who are using our restaurant.  Async Actions along with React UI:  Install the necessary packages as shown below.Command: npm install axios redux-thunkCreate a user’s folder as we are adding user features to this application. In the user’s folder add usersTypes.js to add the types we have learnt in the async actions example we used while learning redux.Now let’s create the usersReducer in the same way that we have learnt.Add our async action creator as well.Now let’s create the usersReducer in the same way that we have learnt.Next, add our usersReducer to the combineReducers and configure redux-thunk middleware in store.js.And we are done with the redux-logic! Let’s add usersContainer.js file in the components folder, write the following code and add it to App.js.App.js now looks as shown below.Now let’s connect our state to the component as shown below.Now if you go to the UI and click the Load Users button, this should show up all the users names that we have fetched from the API.We are done!Reasons to use React Redux:It is the official Redux UI Binding for React.It encourages good React architecture.  It implements Performance Optimizations  It has great community support.Redux has its own drawbacks that need to be overcome. For this, Redux has come up with Redux-toolkit.An Introduction to Redux toolkit:The Redux Toolkit package is intended to be the standard way to write Redux logic. It was originally created to help address three common concerns about Redux:"Configuring a Redux store is too complicated""I have to add a lot of packages to get Redux to do anything useful""Redux requires too much boilerplate code"Read more about redux-toolkit here.Installation:To create a new React app, along with Redux toolkit run the below command.Command: npx create-react-app my-app --template reduxTo add the Redux toolkit to an already existing app:Command: npm install @reduxjs/toolkitOther Resources:Link to learn more about React Redux.To read more about the connect function we have used.Learn React.Summary:In this blog you have all the information you need to work with React-Redux. You have learnt how to implement Redux, and understood the use of actions, reducers, store, action creators, middlewares. You would have understood how to handle async actions, combine reducers, integrate redux to react UI, connect components and also the use of Redux toolkit.Good luck with your React-Redux learning journey!

What is React Redux?

5K
What is React Redux?

React is a JavaScript library for building user interfaces. One of the most popular UI libraries in use today, React is opensource and is maintained by Facebook. React has the best community support, with millions of developers who take part in discussions on best practices, React architecture, and the way forward with React.

You can read more about React here.

In this blog you are going to learn about React Redux. We can use it along with React for state management within the application.

Prerequisites:

  • This blog expects you to have good knowledge of JavaScript.
  • You should have basic understanding of React, React Hooks and Components in React.
  • Please ensure that the latest versions of npm and node are installed in your machine.

To get started with React Redux, let’s first see what Redux is:

What is Redux?

Redux is a predictable state container for JavaScript apps, which means that Redux is predictable and it stores the state of your application. Redux will store and manage the application state.

Redux itself is a standalone library that can be used with any UI layer or framework. Along with React, Redux can be used with many other JavaScript libraries and frameworks such as Angular, Vue and even with Vanilla JavaScript.

You can read more about Redux here.

When we are building a large-scale application, there is a need for a state management tool to avoid prop drilling all through the component. Redux is the most popular and widely used state management tool today.

Note: Redux does what context api does in React. However, Redux was introduced before context api was introduced, and it continues to be the most popular state management library.

In the next part of this article, you will learn to use Redux and in later parts you can learn how to integrate it with your React application.

Learn Redux:

Here you will understand the essential core concepts of Redux before learning how to use it with React.

Start with creating an empty folder with the name Redux-Learnings in your desired location and open the folder in your favourite editor. VScode is preferred.

Initially your project folder looks like this when it is opened in VScode:

It should be empty. Let’s setup our project first.

Now, let’s initialize a package.json file to store all our dependencies to learn Redux.

Open integrated terminal for vscode and navigate to the project location.

Next, run the below command in our terminal to initialize package.json in our project.

Command: npm init –yes

There should be a package.json file inside the project as shown below.

The next step is to install redux as a dependency for our project. Run the below command in the terminal to add redux as a dependency.

Command: npm install redux

If you check package.json file, you can see redux listed under the dependencies as shown below:

Now create a file with the name index.js at the root level of the project and add a simple console statement to see the output on the terminal as shown below.

Now, run the below command to run the index.js file.

Command: node index

It has to print the console statement to the terminal as shown below.

Let’s start learning some theory behind Redux.

Redux has 3 main components:

  1. Store
  2. Action  
  3. Reducer

We will explain these components with the help of a real-world scenario.

Imagine there is a restaurant, and you want to buy a meal. You will go to the restaurant and tell the retailer that you want to BUY a meal. The retailer takes out the meal from the bunch of meals with him, and gives it to you. You will then pay the money for the meal and get the receipt for the purchase. The receipt for the purchase is the proof that the number of meals has been decreased by one.

Let’s see the 3 components in relation to the above scenario:

  1. Store: The store holds all the states of the application. This is similar to the restaurant holding all the meals.  
  2. Action: The Action here is to BUY_A_MEAL which describes what has happened. In this case you have bought a meal. The action describes changes in the state of the application.  
  3. Reducer: Reducers are similar to the retailer. They connect the store to the actions. In this case the retailer is decreasing the number of meals the restaurant (store) has. Reducers update the store according to the action.

To put the 3 components of Redux into code, it’s important to learn the 3 main principles of Redux:

  1. The state of the whole application is stored in a single main object in the store. This means state is a single JavaScript object and lies inside the store. In our example, all the meals of the restaurant are to be represented in a single object. For example: { numberOfMeals: 10}
  2. The only way to change the state is to emit an Action. Emitting an action is the way of letting the Redux know what has happened. It’s an object describing what has happened. In our example BUY_A_MEAL is the action which is describing the action of buying a meal. You are NOT ALLOWED to update the state directly, but you always need an action to update the state.  
    Actions have types. For example: {type: “BUY_A_MEAL”}
  3. To specify how state changes based on actions, we use Reducers. A Reducer is a function that take initial state and action as inputs, and returns new state based on the type the action has. An example of a reducer for the above example is shown below. It decreases the number of meals in the restaurant (store).
const reducer = (state, action) => {
  switch(action.type) {
    case BUY_A_MEAL: 
      return {
        numberOfMeals: state.numberOfMeals-1
      }
  }
}

Now let’s start coding our Redux app.

As you have seen already, the 3 main components of redux are to be implemented in code. Let’s start with Actions.

Creating Action:
As you know that Actions are plain JavaScript objects and have ‘type’ property, which indicates the type of the actions being performed. You are not restricted to just having a type property;  instead, you can have additional properties as well.

Also, in Redux we have action creator. As the name suggests, an action creator is a function which simply creates an action.

Let’s go back to the project we have setup earlier and start coding Actions.  

The Action Type and the Action Creator for our restaurant example can be written as shown below.

Here BUY_A_MEAL is an action type and function buyMeal is an action creator, which returns an action which has type and the description in it.

Creating Reducer:

As we already know, a reducer is a function which takes in initial State and action, and returns a new state based on the type of action.

The reducer can be created as shown below:

Here the reducer is taking in the initial state and the action and returns the new state in the switch statement, where we compare the type in the case block and return the new state object.

…state means that we are creating a copy of the state object and we are changing only the required properties.

However, it's important to keep in mind that in redux we cannot change the state. Instead a new state is created with the changed properties and that is stored inside the Store.

Creating Store:

Before creating a store, its required to know the characteristics of Store:  

  • Store holds the state of the application. 
  • Store provides a method called dispatch which allows updates to the application state. Dispatch method accepts an action as its parameter. 
  • Store allows components to access the state via getState() method. 
  • Registers listeners via subscribe method. That is the listener is called whenever the state is changed inside the store. Listener is a function which is passed to the subscribe method to call whenever the state changes. 
  • Unregister the listeners using the function returned by the subscribe method.

Now let’s implement all the above in the code. 

If you see, we already have the state object by the name initialState in our code. Let’s create a store to hold our state using the redux package we installed earlier.

As shown above, import Redux package using the required syntax. We need to make use of createStore method in Redux to create a store.

Create a store by calling createStore method we pulled out from redux.

createStore takes reducer as the parameter which has the application state.

The store we created has the getState method which gives us the state of the application. To prove this, let’s add the console statement as shown below.

If you run the file using node index command, you can see the console statement is printing the initial state to the console.  

Now let’s quickly implement subscribe and dispatch methods as shown below.

As mentioned earlier subscribe method takes a function as an argument. Here it’s a simple console statement which prints the state.  

dispatch method takes in the action creator as an argument. I have just called it more times to trigger the state transitions more times.

If you run the index file, you can see that the subscribe method is calling the listener function for every state change, and printing the new state as you can see above.  

Now let’s unsubscribe to the listeners by calling the method returned by the subscribe method as shown below.

Capture the unsubscribe method returned by the subscribe method, and call it in the middle to prove that we are unsubscribed to the state changes.

If you can see above, listener has been called only 3 times for the 4 dispatch calls we made, as we unsubscribed before the 4th dispatch call.

What is happening when we call dispatch method?

When we call the dispatch method it dispatches an action buyMeal to the reducer which is returning the action which has a type BUY_A_MEAL. Now the reducer looks at the action type and compares with the case mentioned and returns the new state. As the state changes and the new state gets created in the store, the listener gets called and prints the new state to the console.

This is the flow of redux. Going forward, do make sure that you understand and remember this flow.

What if we have multiple actions?

Let’s take the restaurant example again and say that we have snacks along with meals and we have different retailers(reducers) for each of these.  

So, first step first, you need to update the initialState object to add the number of snacks and action type to buy a snack as shown below.

Now let’s add an action creator to buy a snack (buySnack method).

And also, a reducer case to handle buying a snack case

And also add some dispatch methods to dispatch buySnack action.

Now if you run the index.js file and see the terminal output when buyMeal is dispatched, only the number of meals decreases, and when buySnack is dispatched only the number of snacks decreases.

This method of using a single reducer works in this case. However, in a large-scale application, it gets hard to maintain and debug, also hard to keep track of the work flow.

So, in many cases developers tend to create multiple reducers.  

Create multiple reducers:

For this you need to split the initial state of the application within index.js as shown below

Here, initialState object has been split into 2 state objects; one to store the number of Meals(initialMealState) and one to store the number of Snacks(initialSnackState).

Similarly, we will split the reducer into 2 parts.

Reducer related to Meals.

Here, we have made mealReducer to handle actions related to Meals.

Reducer related to Snacks.

Here, we have made snackReducer to handle actions related to Snacks.

If you observe by splitting the state and reducer, we are maintaining the centralized state and reducer functions for each component or feature in our application. By doing this it's always easy to maintain the code and to keep track of the workflow too.

But if you look at the createStore method there is reducer passed in as an argument but now it no more exists. So, we need to combine the reducers before we pass it to createStore method.

Combining Reducers:

Combining reducers is very simple, and we can do this by using the combine reducers function which redux package offers.

Extract combineReducers function from redux package as shown below:

Now we need to combine all the reducers we have using the method we extracted above.

The combineReducers function takes an object as a parameter which has all the reducers we have created as a key value pairs, and its generally called as rootReducer.

We have to pass that rootReducer as an argument to the createStore method as shown in the above image.  

Now if you run the file using node index you will see something like this inside the terminal.

The meal and snack in the state object corresponds to the meal and snack keys we specified while combining the reducers.

Now we have centralized state and reducers for each of our meals and snacks. We can add more actions to the existing reducers or even add new reducers. Also, it’s easy to maintain the code.

This is the flow of the redux. We dispatch an action which has a type property to the reducer, and the reducer—based on the action type— updates the store accordingly.

In real time applications, the actions are not synchronous as we have learnt above. We may have asynchronous actions, or we may want to add additional functionality to our redux workflow. For all of this we need to use middlewares.

Middlewares:  

Middlewares are the suggested way to extend redux functionality. Middlewares provide third party extension between dispatching an action and the moment the action reaches the reducer.

Middlewares are normally used for logging, crash reporting or to perform some async tasks.  

For example, we will now see how to add a middleware by using redux-logger middleware.  

Read more about redux logger here.

To install redux logger, go to vs code and run the following command in the terminal.

Command: npm install redux-logger

Now if you go to the above-mentioned link for redux logger, you will find the code we write now.  

We need to require the redux logger we just installed and create a logger as shown below.

Now to apply this middleware, Redux has a function built into it which is called applyMiddleware.

Extract applyMiddleware function from redux as shown below.

Now pass the applyMiddleware as a second parameter to the createStore function as shown below.

applyMiddleWare takes all the middlewares we have as arguments. In our case, it is logger.

To see the middleware in action, remove the console.log statement inside the subscribe method of store and run the file using node index. You should see the outputs of the logger in the terminal as shown below.

As mentioned above the actions used in the above example are synchronous actions but in real time applications the actions will be asynchronous.  

As soon as we dispatch an action the state is updated in the above example. But in real time apps we may need to do an API call before we update the state. These types of actions are called asynchronous actions or async actions.

Now let’s see how async actions are handled.

Handling async actions:

For this, let’s make an API call to fetch some users.

So, let’s go to the same project we have been working with, for the above example, and create a new file asyncActions.js and work in this file.

To implement redux, we need 3 things as we have learnt:

  1. State
  2. Actions
  3. Reducers

Let’s look at each one of them.

State:

The state object looks like this:

The loading key in the state object is set to false initially, and it is used to show a spinner when we are making an API call.

The users key in the state object is initially set to an empty array, as we get an array of users after making the API call.

The error key in the state object is initially set to an empty string as if the API call fails, we get the error string and we store the error message in this error key.

Actions:  

The action types and the action creators can be written as shown below.

The fetchUsersLoading action creator can be used when the API call is in progress. So, this returns action type FETCH_USERS_LOADING.

The fetchUsersSuccess action creator can be used when the API call is successful. We get an array of users as an argument for this function which returns the users array as a payload along with action type FETCH_USERS_SUCCESS.

The fetchUsersFail action creator can be used when the API call fails, and we get an error message string as an argument for this function which returns the error message as a payload along with the action type FETCH_USERS_FAIL.

Reducer:

The reducer for the given scenario can be written as shown below.

As mentioned already, FETCH_USERS_LOADING denotes that the API call is going on so loading should be set to true.

FETCH_USERS_SUCCESS denotes that the API call is done and was successful. We can set loading to false again and users to action.payload as we are sending users inside payload in the action creator.

FETCH_USERS_FAIL denotes that the API call is done and failed. We set loading to false again and error to action.payload as we are sending the error message inside payload in the action creator. Users is sent to an empty array as we will not get any users from the API.

Now the last step remaining is to create the redux store.

Create the store in the same way as the previous example.

Now let’s see how to make an api call and actually handle async actions.

To make an api call we use axios. You can read more about axios here.

To define async action creators we use redux-thunk. It is a middleware that must be used in the same way that we used logger in the previous example.

Read more about redux-thunk here.

We need to install both the packages in order to use them. For that, open the terminal and run the following command.

Command: npm install axios redux-thunk

Let’s apply redux-thunk middleware as shown below. By requiring the redux-thunk and making use of applyMiddleWare in the same way as the previous example, we get:

Now let’s write our async action creator which dispatches action creators which we have created earlier.

We will make use of this API.

First import axios as shown below.

Next, make an API call for the above-mentioned end point using axios in our async action creator as shown below.

Here fetchUsers is our async action creator and as we are using redux-thunk we can define async action creators. Redux-thunk allows us to return a function which has access to dispatch method through the arguments so that we can dispatch actions.

We dispatch fetchUsersLoading initially as we are making an api call.

Once the api call is successful we dispatch fetchUsersSuccess along with users as argument.

If the API call fails, we dispatch fetchUsersFail along with the error message.  

This is our async action creator which dispatches the necessary synchronous actions whenever required.

Now write a subscribe method as shown in the above image and dispatch fetchUsers at the last.

In the terminal, to run the file use the below command.

Command: node asyncActions.js

You can see the list of users in the terminal as shown below.

Redux-thunk is widely used middleware to handle side effects such as API calls and other async tasks. It's important that you should learn about this package.

And that’s it! You have completed learning about Redux concepts.

Next, we move on to learning how to integrate Redux with your React application.  

Before we start learning to integrate redux with react, let’s take a look at what react redux is.

What is React Redux?

React is a UI library whereas Redux is a state management library. They both work independently. We cannot use Redux directly in a react application, so we use React Redux to bind Redux in our React applications.

React Redux is the official Redux UI binding library for React. If you are using Redux and React together, you should also use React Redux to bind these two libraries.

This means if we want to use React and Redux together, we also need to use React Redux to bind them together.  

For more information on React Redux, check this link.

Installation:

To directly create a redux app, run the following command inside the terminal.

Command: npx create-react-app my-app --template redux

Navigate into the application using cd command and start making changes to the application.

To integrate redux into an existing react project, run the following command inside the react project.

Command: npm install redux react-redux

This installs redux and react-redux packages to the React application and we can start integrating redux with react.

We are going to follow the second method as we are going to integrate redux with the existing react application.

Let’s try rebuilding the above example with a UI.

We will start with the setup as shown below. This has been created using create-react-app and has been changed according to our needs.

Folder structure:

App.js:

App.js has only one component called MealContainer.

MealContainer.js:

Now if you run the app using the npm start command you will see the similar UI in the browser.

Now, let’s start with integrating redux with our react application.

As mentioned above, install redux and redux-thunk by running the below command.

Command: npm install redux react-redux

After the installation, create a new folder inside src with the name redux. All our redux logic goes into this folder. Now inside this, I would like to create folders with the feature names as all the logic related to a particular feature can be kept organized in a single place. As we have only one feature by the name meals, create a folder with the name meals and 2 files with the names mealActions.js and mealTypes.js to create the actions and action types for this particular feature as shown below.

Inside the mealTypes.js export the action type as shown below.

Note: export keyword is used so that we are able to use the particular function or object in other files by importing them using import key word.

Create an action creator to buy a meal as we have learnt in the previous example.

Now let’s create reducer for our meals feature. For this, create a new file with the name mealReducer.js inside the same folder and create reducer for the meals feature.

Now let’s create the redux store. For this, create a file with the name store.js inside redux folder as store is common for all the features. Next, create a store as we have already learnt, and export it as the default.

Now that we have set up our redux for the application, how does our application get access to the store? Well, for that we need to go to the react-redux package we installed; this is where react-redux makes its first appearance. We need to go to Provider which react-redux offers in order to make our app know about the store.

Go to the app.js file and import Provider from react-redux, and wrap the whole app with this provider passing store as a prop to it.

Now what remains is to connect redux to our components, dispatch an action and update the store from the components.

Connecting redux to the components:

As a first step, write a couple of functions mapStateToProps and mapDispatchToProps as shown below.

mapStateToProps is a function that you would use to provide the store data to the component as prop. Whereas mapDispatchToProps is something that you will use to provide the action creators as props to the component.

Read more about the 2 functions here.

We import buyMeal action from the action file to use in mapDispatchToProps.

Now to connect both the functions to the component, we need to import connect which react-redux offers us as shown below.

Now using that, we connect the state and actions to the component as shown below.

mapStateToProps and mapDispatchToProps are passed as arguments to the connect function.

Now we can access the numOfMeals using the props object and show that in the UI.

The numOfMeals upon the props pertains to the key returned by the object in the mapStateToProps.

If you save and check the UI, you can see the number of meals displayed.

Now let’s dispatch our buyMeals action. This is available on the props object, as we have used mapDispatchToProps. Upon the click of the button, we execute the function which dispatches our action as shown below.

Now if you click the button in the UI, the meals should decrease by 1.

Now, let’s integrate logic for the snacks as well.  

Add SnackContainer.js file similar to mealContainer and add it in the App.js file as shown below.

In the redux folder, add a new folder for snacks feature and add the necessary files in the same manner as the meals folder.

snackTypes.js

snackActions.js

Next, write the reducer in the snackReducer.js

As we have 2 reducers, we need to combine reducers as we have learnt previously, and pass the rootReducer to the store.

Due to this change, the application will break as we have changed the structure of the state in the store. So, we need to make some changes in mealContainer as shown below.

Let’s connect the state to the snackContainer component in the same way that we have done in the mealContainer component, as shown below.

If you check the UI, you will be able to see the number of snacks displayed as shown below.

If we click on the Buy Snacks button, that should decrease the number of snacks by 1.

And that’s it! We have implemented React-Redux along with the React UI.

Let’s see how to manage Async actions in UI.

If you see, we have rewritten the same code we have used to learn Redux.

Let’s implement the same API call example we have learnt above in React. We will consider that these are the users who are using our restaurant.  

Async Actions along with React UI:  

Install the necessary packages as shown below.

Command: npm install axios redux-thunk

Create a user’s folder as we are adding user features to this application. In the user’s folder add usersTypes.js to add the types we have learnt in the async actions example we used while learning redux.

Now let’s create the usersReducer in the same way that we have learnt.

Add our async action creator as well.

Now let’s create the usersReducer in the same way that we have learnt.

Next, add our usersReducer to the combineReducers and configure redux-thunk middleware in store.js.

And we are done with the redux-logic! Let’s add usersContainer.js file in the components folder, write the following code and add it to App.js.

App.js now looks as shown below.

Now let’s connect our state to the component as shown below.

Now if you go to the UI and click the Load Users button, this should show up all the users names that we have fetched from the API.

We are done!

Reasons to use React Redux:

  • It is the official Redux UI Binding for React.
  • It encourages good React architecture.  
  • It implements Performance Optimizations  
  • It has great community support.

Redux has its own drawbacks that need to be overcome. For this, Redux has come up with Redux-toolkit.

An Introduction to Redux toolkit:

The Redux Toolkit package is intended to be the standard way to write Redux logic. It was originally created to help address three common concerns about Redux:

  • "Configuring a Redux store is too complicated"
  • "I have to add a lot of packages to get Redux to do anything useful"
  • "Redux requires too much boilerplate code"

Read more about redux-toolkit here.

Installation:

To create a new React app, along with Redux toolkit run the below command.

Command: npx create-react-app my-app --template redux

To add the Redux toolkit to an already existing app:

Command: npm install @reduxjs/toolkit

Other Resources:

Link to learn more about React Redux.

To read more about the connect function we have used.

Learn React.

Summary:

In this blog you have all the information you need to work with React-Redux. You have learnt how to implement Redux, and understood the use of actions, reducers, store, action creators, middlewares. You would have understood how to handle async actions, combine reducers, integrate redux to react UI, connect components and also the use of Redux toolkit.

Good luck with your React-Redux learning journey!

KnowledgeHut

KnowledgeHut

Author

KnowledgeHut is an outcome-focused global ed-tech company. We help organizations and professionals unlock excellence through skills development. We offer training solutions under the people and process, data science, full-stack development, cybersecurity, future technologies and digital transformation verticals.
Website : https://www.knowledgehut.com

Join the Discussion

Your email address will not be published. Required fields are marked *

Suggested Blogs

Everything You Need To Know About Angular 12.0.0 Release

Angular is a product of the most renowned Google TypeScript based framework, dedicated to developers for building web applications for smartphones and desktops. Over the years, the Angular framework has shown significant growth and is now a favourite tool among developers. The popularity of Angular can be attributed to the fact that it has been reliable and offers unmatchable features which are easy to use, when compared to its competitors, since its official launch.The popularity and increasing demand for the Angular framework are scaling new heights. From its first release to date, the Angular framework has attracted developers and has been marked as the favourite of over twenty-six percent (26%) of web developers worldwide. Angular provides unmatchable features that make it the most preferred framework in the Web Development industry today.   The frequent updates by the Angular team are just another reason to fall in love with this most versatile and robust framework. With every subsequent update, the Angular team brings in new features, extended capabilities, and functionalities that make the user experience effortless and web development enjoyable.   Glad tidings for Angular developers! Angular 12 tries to improve on fixing bug issues in the previous versions that were raised by the Angular community. Finally, the wait is over! The Angular version 12.0.0 release has come up again with the most compelling features and customization options to take your development journey to a new horizon. The new release of the Angular 12.0.0 version brings updates on the framework, the CLI, and components. What’s new in this update? The Angular team has been releasing major features in their upgrades, while ensuring that the number of backward compatibility issues is kept at a minimum and making sure that updating to the new version is easy. We have seen significant improvements in these areas of built times, testing, built-size, and development tooling. Before the release of Angular on the 21st of April, 2021 there were 10 beta versions of the same.  Updates in Angular 12 include the following: For the language service, they have added a command to add a template file. Making minified UMDs essential. Redirected Source files. Component style resources. Introduction of a context option.  New migration that casts the value of fragment nullable. DOM elements are correctly removed when the root vies have been removed. Improved performance since unused methods have been removed from DomAdapter. Legacy-Migrate. Strict Null checks. App-initializer has been changed. Support has been added for disabling animations.  Angular 12 can disable animations through BrowserAnimationsModulewithconfig. Addition of the emit event option. More fine-tuned controls in routerLinkActiveOptions. Custom router outlet implementations are permitted. Support for type screen updated. Implementing the append all() method on Httpsparams. Minimum and maximum validators are introduced. Exporting a list of HTTP status codes. New Feature in Angular Service. Patch adding the API to retrieve the template type check block. NOTE: Several bug fixes have also been highlighted, affecting the compiler, compiler-CLI, Bazel-built tool, and the router. Let’s have a look at the unique and unparalleled features in Angular 12.0.0:  1. Better developer ergonomics with strict typing for @Angular/forms. The Angular team has focused on enforcing secure and strict methods of checking for reactive forms. The new update will help developers to look out for issues in the development stage. This upgrade will also enable better text editor and ide support allowing the developer better developer ergonomics with strict typing for Angular/forms. The previous versions were not as aggressive in addressing this issue, but Angular 12 does it perfectly. 2. Removing legacy View Engine. When the transition to Ivy of all internal tooling gets done, removing the legacy View engine becomes the next challenge. No worries! The newly added removing legacy View Engine aims to reduce framework overheads. This is because of smaller Angular conceptual overhead, smaller package size, saving on maintenance cost, and decrease in the complexity of the codebase. With the knowledge of Ivy, it's the best path to take while using the latest version of Angular. An application that has upgraded to the latest version of Angular (Angular 12.0) and is keeping enable Ivy as false, should consider this since in the future they cannot upgrade to the latest version if they don't start using Ivy. 3. Leverage full framework capabilities.  Design and implement a plan to make Zone.js optional. This will, in turn, simplify the framework, improve debugging, and minimize application bundle size.Zone.js does not support native async/await syntax and when Zone.js is optional and a developer can choose not to use it then Angular will be able to support native async/ await syntax. 4. Improving test time, debugging, and test time environment. Testbed automatic clean-up and tear down of the test environment after each test run, will improve test time and create better isolation across tests. 5. Easier Angular mental model with optional modules. This will simplify the Angular mental model and learning. This will allow the developers to develop standalone components and implement other types of APIs for the declaration of the component compilation scope. On the other hand, we have to note that this change might make it hard for existing applications to migrate to this. This feature will allow developers to have more control over the compilation scope for a particular component without giving much thought to the NgModule they belong to. 6. Adding Directives to Host Elements. Adding directives to host elements has been on high request by Angular developers for a long time. The new release allows developers to architecture their components with additional characteristics without using inheritance. At the moment you cannot add directives to host elements, but you can improvise using: host CSS selector. As the selector of these components also becomes a DOM element, we could have more possibilities if we could add more directives to this element too.7. Better Build performance with NGC as TypeScript plugin distribution.The Angular compiler being distributed as a TypeScript plugin will significantly improve the developer's build performance and reduce the cost. 8. Ergonomic Component level code-splitting APIs. The slow initial load time is the major problem with web applications. Applying more granular code-splitting on a component level can solve this problem. This will mean smaller builds and faster launch time and in return result in improved FCP.  That's all for the new release. Now, let us take a look at the possibilities that are in progress and will be available shortly. Inlining critical styles in universal applications. Firstly, this will result in faster applications. Loading external stylesheets is a blocking operation. This means that the browser cannot initiate rendering an application without first loading all the referenced CSS. Its FCP (First Contentful Paint) can be improved by having a render-blocking in the header of a page that can visibly improve the load performance. Angular language service to Ivy. To date, the Angular language service still uses the View Engine compiler and type checking even for Ivy applications. The goal is to improve the experience and to remove the legacy dependency. This will be achieved by transitioning from View Engine to Ivy. The team at Angular wants to start using the Ivy template parser and improved type checking for the Angular language service to match Angular application behaviour. This will simplify Angular, npm size reduction, and improve the framework’s maintainability. Debugging with better angular error messages. The error messages bring limited information on how a developer can take actions to resolve them. The Angular team is working on codes, developing guides, and other measures to ensure an easy debugging experience and make error messages more discoverable. Better security with native Trusted Types in Angular. In conjunction with the Google security team, the Angular team is working on adding support for the new Trusted Type API. This API will aid developers to make more secure web applications. Optimized build speed and bundle size.With Angular, the CLI Webpack 5 stability will continue urging for the implementation to enable build speed and bundle size improvements. Advanced Angular Material Components. Integrating MDC weblink will align Angular Material closely with the material design specification, expand the accessibility reach, improve component quality and improve the overall team velocity. Faster debugging and performance profiling. The team at Angular could focus its attention on working on tooling that will help in the provision of utilities for debugging and performance profiling. The primary aim is to help the developers understand the component structure and the means to note changes in the angular application. NOTE: MDC web is a library created by the Google Material Design team that provides reusable primitives for building material design components. Conclusion.   In this article, we have looked at the Angular 12.0.0 version that released on 21 April 2021, the predecessor of which was Angular 11. We have tackled all the new features and provided an in-depth explanation of the same. We have taken a look at the trajectory of the Agular team whilst discussing the possibilities of new features to come in future versions of this product.  Angular is becoming more robust, and the applications created on this platform are getting more performant with every new update of the product. The framework is the future of this product, and this does not mean they are all necessarily in version 12.0.0. There are more points to be added to this list for internal improvements, such as work on the Angular team performance, dashboard, and so forth. Angular developers may be looking out for more advanced features like those present in Ivy-based language service. Perhaps those are slated for the next release! Attention Coders: If you want to know more about Angular version 12 and plans for the framework, you can visit their website
7313
Everything You Need To Know About Angular 12.0.0 R...

Angular is a product of the most renowned Google T... Read More

What Is Replication in MongoDB

What is Replication? Replication is the process of storing the data in multiple places instead of just one. Data is stored on multiple servers across different physical sites, in order to improve data availability and also ensure uninterrupted access to data even if one of the sites goes down due to some failure. Simply put, replication involves copying of the data from one server to another. As the changes occur on the primary server, they are simultaneously propagated to the other servers as well. This keeps all of the servers in sync and the read operations can be performed on any of the available sites. The result is a distributed database in which users can access data relevant to their tasks without interfering with the work of others. Replication in MongoDB In MongoDB, mongod is the primary process in the system that handles data requests, manages data access, and also performs various background management operations. For Replication to work, it is important to have multiple mongod instances running that maintain the same dataset.  A replica set is the foundation of replication. The server instances that maintain the same dataset form a replica set in MongoDB. A replica sets ensures redundancy and high availability, and is the basis for all production deployments. Each replica set contains multiple data bearing nodes and optionally an arbiter node. Of all the data bearing nodes, one and only one member is designated as the primary node, while the other nodes are designated as the secondary nodes. The primary node receives the requests for all the write operations from the clients. The write operations are then synced to the secondary nodes using various algorithms. The primary records all writes and other changes to its datasets in its operation log, i.e. oplog.To enable replication in MongoDB, a minimum of three nodes are required. In this operation of replication, MongoDB assumes one node of replica set as the primary node and the remaining are secondary nodes. From within the primary node, data gets replicated to secondary nodes. New primary nodes get elected in case there is automatic maintenance or failover. Redundancy and Data Availability If replication is in place, it simply means that there will be multiple copies of the same data in different database servers. This ensures high data availability and data redundancy. High availability indicates a system designed for durability, redundancy, and automatic failover such that the applications supported by the system can operate continuously and without downtime for a long period of time. Due to redundancy, replication provides fault tolerance against the loss of one or more (not a lot) database servers. In certain cases of data replication, clients can send read operations not just to one server, but to different servers. This results in increased read capacity and faster responses to requests from clients. Maintaining copies of data in different servers increases data locality and availability for distributed applications. These duplicate copies of data can be used for various recoveries, reporting or backup purposes as well. Enabling Replication in MongoDB As we already know, a replica set is a group of mongod instances that maintain the same data set. A replica set contains several data bearing nodes and, in some cases, one arbiter node which is optional. Of all the data bearing nodes, one and only one member is designated to be the primary node, while all the other nodes are assigned to be secondary nodes. The point of an Arbiter is to break the deadlock when an election needs to be held for a Primary.  If you have an odd number of nodes, the election process is simple when all nodes are up, and in a failover, one of the other nodes will simply be elected. If you have an even number of nodes in a replica set, an Arbiter may be required. An example is a case where you do not want to commit the same level of hardware to have, say, a five-node replica set. Here you could use an arbiter on a lower specification machine in order to avoid a deadlock in elections. An arbiter is also useful if you want to give preference to certain nodes to be elected as the Primary.The primary node receives all write operations. A replica set can have only one primary capable of confirming writes with { w: "majority" } write concern. The primary records all changes to its data sets in its operation log, i.e. oplog. The secondaries replicate the primary’s oplog entries and apply the operations to their datasets such that the secondaries’ datasets completely reflect the primary’s dataset. If the primary is unavailable, an eligible secondary holds an election to elect itself as the new primary.  In some cases where, for example, cost constraints allow only one primary and secondary but do not allow addition of more than one secondary, an arbiter is used. An arbiter node does not hold any data at al. It only participates in elections. Hence, it does not provide any data redundancy.  An arbiter will always be an arbiter, whereas a primary may step down and become a secondary, and a secondary may become the primary during an election. Follow the following steps to enable replication and create a replica set.Ensure that all servers can access each other over the network. For now, consider that we have 3 servers, ServerA, ServerB and ServerC. Considering the ServerA is the primary and only server working as of now, issue the following commands on server A. mongo –host ServerB –port 27017 mongo –host ServerB –port 27017 Execute the same commands on the remaining servers as well. Start the first mongod.exe instance with the replSet option. This option provides a grouping for all servers which will be part of this replica set. mongo –replSet "Replica1"The first server is automatically added to the replica set. Next, let’s initiate the replica set. rs.initiate() To add more servers to the replica set, issue the following commands.rs.add("ServerB")rs.add("ServerC")You’re done! Run the rs.status() command. This command gives the status of the replica set. By default, each member will send messages to each other called "heartbeat" messages which just indicate that the server is alive and working. The "status" command gets the status of these messages and shows if there are any issues with any members in the replica set. Benefits of Replication We already know that Replication allows us to increase data availability by creating multiple copies of the data across servers. This is especially useful if a server crashes or if we experience service interruptions or hardware failure. Let’s have a look at some other advantages of Data Replication. Replication helps in disaster recovery and backup of data. In case of a disaster, secondary nodes ensure that the data is always available without service interruptions. Replication ensures that data is always available to every client. Replication keeps the data safe and protected through this redundant backup approach. Replication minimizes downtime for maintenance. Asynchronous Replication Asynchronous replication is a replication technique where data is backed up periodically or after a period of time. It is not immediately backed up during or immediately after the data is written to the primary storage. This kind of replication results in good performance and lesser bandwidth requirements, but the backups are not readily available if something happens to the primary storage.In an asynchronous replication system, the data is written to the primary storage first and then it is copied over to the secondary nodes. The copying or replication is done at predetermined intervals. How and when this is done, depends on the settings and the type of implementation of asynchronous replication.This method allows for good read/write performance without adversely affecting the bandwidth usage as data is not replicated to remote backups in real-time, as in a synchronous replication system. So the system in not under a lot of load at any given point of time. Data is only backed up after predetermined times or periodically. This does not guarantee 100% backup, so it should be used for less sensitive data or information that has tolerance for loss. In a situation where a disaster or failure occurs right after the data is written to the primary storage, the data will not be copied over to the secondary nodes and therefore will cause loss of data and affect availability. Replication vs Sharding Sharding is a process where the scaling is done horizontally by partitioning data across multiple servers using a special key called Shard Key. A sharded environment does add more complexity because MongoDB now has to manage distributing data and requests between shards -- additional configuration and routing processes are added to manage those aspects.Replication, on the other hand, creates additional copies of the data that allows for better availability and read performance. Typically, replication and sharding are used in combination. In these situations, each shard is supported by a replica set.Shards in MongoDB are just replica sets with a router in front of them. The client application connects to the router, issues queries, and the router decides which replica set (shard) to forward the request to. It is significantly more complex than a single replica set because we have the router and configuration servers to deal with.Sharding is done with the objective of scaling the database horizontally.Transactions Multi-document transactions are available for replica sets (starting from version 4.0). Multi-document transactions that contain read operations must use read preference primary. All operations in a given transaction must route to the same member.The data changes made in the transaction are not visible outside the transaction until a transaction commits. Once the transaction commits, changes are then available to be read by all secondaries and clients.However, when a transaction writes to multiple shards, not all outside read operations need to wait for the result of the committed transaction to be visible across the shards.Change streams In replication, as we have read above, the secondary nodes replicate the primary node’s oplog entries and end up having exactly the same dataset as the primary. Another alternative to this approach is that whenever there is a write to the primary node’s data, it informs all the secondaries of this data change and the secondary nodes then update themselves accordingly. This is possible with the help of change streams.Change streams allow applications to subscribe to all data changes on a collection or a set of collections. This way all the apps are notified of the changes to the data.Replica sets provide a number of options to support various application needs including data backup, recovery and increasing availability. They increase performance and data availability. Replication also ensures that the downtime, if there is any, is brought down to lowest in case of disaster or any other event that causes interruptions in accessing data.
7350
What Is Replication in MongoDB

What is Replication? Replication is the process o... Read More

Difference between State and props in ReactJs

In this article, we will discuss the states and props in ReactJS. Props and state both provide the details about the item but have differences. Let’s take a look at how to pass props into the component and how to update a component’s state.What is State?The status of a react class component instance can be described as an object of a collection of observed features that control the component’s behavior. In other words, the component’s state is an entity with some details that can alter during the component’s lifetime.This data is kept inside a component. This particular aspect is local or owned. The component itself uses the setStatus function to update the state. The state is an updated structure that is used to contain and can modify data or information about the component over time. The state change may occur as a user activity or device event response. It decides the actions of the component and how it is to be done by the core of the React component. As easily as possible, a state should be held. It is the local state or details of the part. Only in the component or by the component directly can it be accessed or changed. Components of react have a built-in state object. The state object is where the property values belonging to the item are stored. The component is restored when the state object changes.What are Props?React is a library focused on components that separate the user interface into reusable little bits. These components have to transmit (send data to each other) in some cases, and the way to transmit data among components is through props. “Props” is a special React keyword for proprietary purposes, used for data transmission from component to component. But the key part of this is the transmission of data with props in a uniform flow. (parent-to-child route)In addition, props data are read-only, meaning that parent data cannot be modified by child elements.Difference between State and PropsReact is an opensource JavaScript library that offers a visual overview of the JavaScript architecture for conventional MVC. React promises programmers a model in which substrates cannot directly influence enclosing components—data are downstream, data changes in HTML are efficiently modified, and the DOM is abstracted to boost performance using Virtual DOM.How can we access data from the previous component if the data is just being flowed from components to components? The answer is props. React uses data transmission props that we need to transfer to various components. The difference comes in which component the data are owned. State is owned locally and the component itself updates it. Props are owned and read-only by a parent. Props can be changed only if an upstream shift is caused by a callback function passed on to the child.A prop can be passed on to the child in the state of a parent. They apply to the same value but can only be updated by the parent variable.How are props passed into the component?We can pass props to any component by declaring HTML tag attributes.We transfer a sampleProp in the above code snippet to the DemoComponent part. This prop has the ‘HelloProp’ value. See how we can access this advice now.In the class components to which the props are transferred, we can access any props.this.props.propName;We can use the above syntax to access any prop from within a component class. The “this.props” is a type of total object that stores all props from an item. The propname, which is the propName, is the key.Passing information from one component to other:This is one of React’s coolest characteristics. We should make it possible for components to communicate. To understand this, we will look at two components Parent and Child. We will pass information to the Child component as advice from our parent component. We can offer a part as much advice as we want. The content of a prop is not permitted to be changed. No matter what kind of component it is, nobody is allowed to change their advice, whether functional or class-based. The difference comes in which component the data are owned. State is owned locally and the component itself updates it. Props are owned and read-only by a parent. Props can be changed only if an upstream shift is caused by a callback function passed on to the child. A prop can be passed on to the child in the state of a parent. They apply to the same value but can only be updated by the parent variable.How do you update a component’s state?Although a react component can have an initial state, the actual power is in updating the state — the component should not be in either state if we don’t have to update the state. State is reserved only for data that changes our part and can be seen in the user interface.We use this.setState() instead of changing the state directly using this.state (). This is a feature for all components that use state, and allows us to inform React that the state of the component has changed. This way the component knows that it can return because its status has changed and the user interface will probably change as well. It is very efficient to use a setter function like that. React intentionally waits until all components in their event handlers call setState() before they start returning. This increases efficiency by preventing excessive re-renders. You may also ask why React does not update this, however. Two major reasons exist: The consistency of props and the state is broken, which causes problems that are very difficult to debug. This will make it difficult to introduce such new features. React will load several setState() calls for performance into a single update. Due to the asynchronous of this.props and this.state, you cannot depend on their values for the next state to be calculated. To fix it, use a second setState() form, which accepts a function instead of an object. This function is the first argument for the previous state, and the props are the second argument when the update is applied: this.setState(function(state, props) {   return {     counter: state.counter + props.increment   }; });Is state changeable?A state change takes place on the basis of the user input, which triggers an occurrence. React (with status) components are often made on the basis of state data. The initial knowledge is held by the State.Thus when the state changes, React will be notified and the DOM will be re-rendered immediately; not the whole DOM but only the modified portion. This is one of the reasons for the fast reaction.And how do you notify React? You thought: with setState ( ). The setState() method triggers the mechanism for rendering the modified components. React is notified, knows which part(s) to alter, and does so quickly without restoring the entire DOM.Is state created in the component?Let’s see the constructor method:constructor() {   super();   this.state = {     count: 0,   }; }This is where the state gets the initial data. The initial data (as above) can be hard-coded, but it can also come from props.However, it makes sense – you cannot adjust props but the data a component receives wants to do so. This is where the state enters.Component typesStateless component — Just props, no state.  Besides the render() function, there’s not much going on and all its logic is about the props that they get. This makes it easy to track them (and test for that matter).  The stately component — state as well as props. These are also called state managers. They are responsible for communication between clients and their servers (XHR, Web sockets, etc.), data processing, and user events.What happens when state changes?React Components allow you to break the UI into separate, reusable components so that you can look into every single item on an isolated basis.Components are conceptually like functions in JavaScript. They accept arbitrary inputs and return elements of react that describe what should be shown on the screen. If you have to allow the user to enter something or to alter the variables that the component is supported by, you would have to setState.State allows React components in response to user behavior, network responses, and everything else to adjust their performance over time, without violating this rule. Class-defined components provide additional functionality. Local status is the only class component function available.Can I use state in every component?In the early days, only class components, and not functional components, were included.That’s why stateless components are known for their functional components. However, state can now be used in both class and functional components following the implementation of React Hooks.You can only use status in class components if your project does not use React Hooks.The component State and Props share some common similaritiesProps and states both provide details about the item, but they are used differently and must be kept separate.ConclusionState refers to the component’s local status which cannot be used and changed outside the component and can only be used and modified within the component. On the other hand, it provides reusable components by enabling components to obtain data in the form of props from the parent component. We may change the state of a component with setState. These notifications are also triggered by events. setState is called asynchronous and merged with every entity in the current state. We may also transfer a setState function to allow us to write status changes based on the current status values. Most of your components can be stateless when you create an app. Props transfer parent-to-child data. They are unchangeable and are thus unchanged.
1680
Difference between State and props in ReactJs

In this article, we will discuss the states and pr... Read More