Search

Blogs blog posts

Installation of React on Mac

Hello learners! In this tutorial we are going to learn the installation of React.js library on macOS. React.js is a library which helps developers to develop highly efficient data-driven SPA apps. It is based on functional programming, relies on the concept of immutability and encourages component-based architecture based on Single reusability principle.Before we perform the installation steps, we need to look at the prerequisites needed for installation.1. PrerequisiteSystem requirements: mac OS > 10.10Minimum RAM: 4 GBStorage space: 10 GB available spaceInternet browser: Chrome, Safari, Opera, Microsoft EdgeInternet connectivity: 512 kbps and above2. Introduction to ReactIn this tutorial, we will install the react library on macOS. Before the installation, we need to have a quick understanding of React.React is a library which helps web developers and architects to serve the needs of customers having demands of high data flow and fast responsive UIs in the context of data.It is based on the components-based architecture. The webpage can be represented in the form of Parent and Child based components.  It relies heavily on Virtual DOM, which acts as a performance optimization to DOM operations.A Web page which is composed of HTML has a DOM tree, with the help of which the web page is rendered by the browser.When the user is interacting on a page, it involves addition and insertion of information based on the user activity.  for e.g. A user has added an item to the cart. The cart is showing the updated item to reflect the user’s decision.Behind the scene, the HTML document undergoes a certain transform which helps to share the updated page. As we have mentioned, the HTML document is represented by the DOM tree. In the above scenario, the DOM needs some changes which involve addition and deletion of certain HTML nodes. This helps to show the relevant information which represents what a user is trying to achieve in the context of updating his buying choice.For this insertion and deletion operation on HTML DOM, there is a memory cost involved.Virtual DOM acts as a performance optimizer as far as the DOM update operations are concerned.  It maintains two copies; one is the real copy of the DOM (react DOM) and another one is the change to be done. The process by which minimal change takes place on the react DOM is also studied under the process called reconciliation.To understand the DOM we can visualise it as a tree.  The tree has roots and branches. In a similar manner the DOM has the HTML element at the top and down below there are nodes which are connected to the parent node. In terms of tree analogy, we can represent the parent node as the trunk, with various nodes connected to the trunk. And on these nodes, the insertion and deletion operations get optimized by using React.3. A short intro to Node.js & npmRyan Dahl is the inventor of Node.js.Node.js code is an open source, cross-platform, JavaScript runtime environment that runs JavaScript code. It is based on the Chrome V8 engine. Chrome V8 engine is written in C++. It runs on Windows, macOS and Linux.After installation of Node.js, we can run the react based project locally on our system during development. This also allows us to deploy our app on the production server.Some of the features of Node.js include:a. Uses JavaScript as primary languageb. Non-blocking I/Oc. Supports Asynchronous programmingd. Can handle multiple connections requests by using a single serverNode.js allows us to perform read, write operations on the server.It also provides the functionality to work with the databases.Npmjs.org is an online code repository of thousand modules (npm) and it allows us to install node modules using basic commands. Some modules are independent and some are interrelated to run effectively, due to dependencies between them.Node.js hosts several modules and instead of building functionality from scratch, it is easier for us to look for a module and reuse and extend its functionality. Developer projects generally have time and budget constraints. For the developer community, npmjs.org acts as a lifesaver as far as the Node.js based development is concerned.4. Download Node.js and installationTo install Node.js there are various steps.  It can be installed by visiting https://nodejs.org/en/download/Once we have downloaded the Node.js version based on the operating system, we can perform the installation steps.One thing we need to note is that NPM is auto-installed with Node.js installation.We need to click on the package file which we have downloaded node-v14.15.1.pkgIn the below installation we can see it will install Node.js  v14.15.1 and npm v6.14.8When we click on the Continue button, the installer will ask to ‘Read Licence’.  It also shows two-buttons-- Disagree and Agree.To install the Node.js we need to click on Agree.To proceed further we need to specify the Login password to continue the installation.In the below screenshot the user has administrative rights for software installation. So, the admin needs to type the password in order to proceed further.After clicking on the Install Software button, click on the Install button.In the next screen, the progress bar will indicate the installation progress.Post-installation, it will provide us with a summary as below.After closing this window by clicking on the close button, we need to verify whether we have installed the said version of Node.jsTo open command terminal, press Command + Space barThis will open Spotlight search as below.We need to type Terminal and hit enter.Once the terminal is visible, we need to type the following commandnode - vAs we can see it is showing us the node version (v14.15.1) as in the screenshot.So, we have installed Node version 14. Each build is denoted by semantic versioning. The first digit, in this case, is 14, which represents a major release. The second digit represents new features with the release and the third digit represents patch and bug fixes as associated with the major release.Node.js installation by command line.As an alternative method, we can install node.js by the terminal as well. But as a prerequisite, we need to have homebrew (https://docs.brew.sh/Installation)  in MacOS.We are assuming, we have homebrew installed in our system.And to proceed with the command-line installation, we need to open the terminal and type the following command.brew - vThe above command will inform us about the homebrew version.To update the brew, type the following commandbrew updateAfter the above command has been executed, we need to typebrew install nodeThe installation will take some time, so give some time to the system and be patient.To verify the Node.js installation usenode -vTo verify the npm installation usenpm -vCongratulations, we have installed Node.js and NPM.5. Create-react-app for react app on macOSNow, we are going to install create-react-app on macOS.Create-react-app is a quick way to set up a single page application code with minimal steps and no configuration.Let’s proceed with the installation steps.Please type the following command in the terminal to create a folder with the name react-app. mkdir react-appThen navigate to directory react-app as follows:cd react-appTo verify directory, type command and enter as belowpwdOnce we have confirmed that we are in the right directory type below command.npx create-react-app my-appnpx is a module which is included with npm.The installation steps as shown in the above screenshot will take some time.So, sit back and relax.Once the above command has been executed successfully....….navigate to my-app directorycd  my-appAnd typenpm startWhen the command is executed successfully, it will open the browser at localhost:3000 in the browser.And we can give ourselves a pat on back for the small win!6. Download and Install React (Explicit command)This step is for awareness only.In the previous step, we have not explicitly installed React.js as this is installed with the help of create-react-app package.We can also install the React.js  by using the following command.  And we may need to install the module dependencies on our own.npm install react --save7. File folder and structureWe can see that we have not touched the codebase but found the minimal single page web application running on our macOS.To see the code structure, we need to open the code editor e.g. Sublime, Atom etc.And open the folder my-appAs we can see, there are various folders and at a high level there are below folders:node_modules public srcIn the public folder, we can see index.html. This is the page template.The index.js in src folder is the JavaScript entry point.The app is displaying the code from the App.js in the src folder.In the my-app folder, the package.json is an important file which mentions the app name and module dependencies. Feel free to explore further.8. Summary (conclusion)In this tutorial, we have learnt about React.js, and the component-based architecture model in React.js. We also had a high-level overview of the virtual DOM.We touched on the concept of reconciliation, the usage of Node.js in the world of JavaScript and its capability to handle non-blocking I/O output to fulfil client connection requests simultaneously.We have checked two methods for Node.js installation, namely with the package manager and another one by using the command line.To install React.js, we have relied on the create-react-app module for a quick start. We can also install the React.js by command line. To prevent being overwhelmed with too many details we have picked the create-react-app method for this tutorial. We created our first react app and saw it running.To become familiar with the code in terms of development perspective, we quickly checked the important files which are running the app.
Installation of React on Mac
Gaurav

Installation of React on Mac

Hello learners! In this tutorial we are going to learn the installation of React.js library on macOS. React.js is a library which helps developers to develop highly efficient data-driven SPA apps. It is based on functional programming, relies on the concept of immutability and encourages component-based architecture based on Single reusability principle.Before we perform the installation steps, we need to look at the prerequisites needed for installation.1. PrerequisiteSystem requirements: mac OS > 10.10Minimum RAM: 4 GBStorage space: 10 GB available spaceInternet browser: Chrome, Safari, Opera, Microsoft EdgeInternet connectivity: 512 kbps and above2. Introduction to ReactIn this tutorial, we will install the react library on macOS. Before the installation, we need to have a quick understanding of React.React is a library which helps web developers and architects to serve the needs of customers having demands of high data flow and fast responsive UIs in the context of data.It is based on the components-based architecture. The webpage can be represented in the form of Parent and Child based components.  It relies heavily on Virtual DOM, which acts as a performance optimization to DOM operations.A Web page which is composed of HTML has a DOM tree, with the help of which the web page is rendered by the browser.When the user is interacting on a page, it involves addition and insertion of information based on the user activity.  for e.g. A user has added an item to the cart. The cart is showing the updated item to reflect the user’s decision.Behind the scene, the HTML document undergoes a certain transform which helps to share the updated page. As we have mentioned, the HTML document is represented by the DOM tree. In the above scenario, the DOM needs some changes which involve addition and deletion of certain HTML nodes. This helps to show the relevant information which represents what a user is trying to achieve in the context of updating his buying choice.For this insertion and deletion operation on HTML DOM, there is a memory cost involved.Virtual DOM acts as a performance optimizer as far as the DOM update operations are concerned.  It maintains two copies; one is the real copy of the DOM (react DOM) and another one is the change to be done. The process by which minimal change takes place on the react DOM is also studied under the process called reconciliation.To understand the DOM we can visualise it as a tree.  The tree has roots and branches. In a similar manner the DOM has the HTML element at the top and down below there are nodes which are connected to the parent node. In terms of tree analogy, we can represent the parent node as the trunk, with various nodes connected to the trunk. And on these nodes, the insertion and deletion operations get optimized by using React.3. A short intro to Node.js & npmRyan Dahl is the inventor of Node.js.Node.js code is an open source, cross-platform, JavaScript runtime environment that runs JavaScript code. It is based on the Chrome V8 engine. Chrome V8 engine is written in C++. It runs on Windows, macOS and Linux.After installation of Node.js, we can run the react based project locally on our system during development. This also allows us to deploy our app on the production server.Some of the features of Node.js include:a. Uses JavaScript as primary languageb. Non-blocking I/Oc. Supports Asynchronous programmingd. Can handle multiple connections requests by using a single serverNode.js allows us to perform read, write operations on the server.It also provides the functionality to work with the databases.Npmjs.org is an online code repository of thousand modules (npm) and it allows us to install node modules using basic commands. Some modules are independent and some are interrelated to run effectively, due to dependencies between them.Node.js hosts several modules and instead of building functionality from scratch, it is easier for us to look for a module and reuse and extend its functionality. Developer projects generally have time and budget constraints. For the developer community, npmjs.org acts as a lifesaver as far as the Node.js based development is concerned.4. Download Node.js and installationTo install Node.js there are various steps.  It can be installed by visiting https://nodejs.org/en/download/Once we have downloaded the Node.js version based on the operating system, we can perform the installation steps.One thing we need to note is that NPM is auto-installed with Node.js installation.We need to click on the package file which we have downloaded node-v14.15.1.pkgIn the below installation we can see it will install Node.js  v14.15.1 and npm v6.14.8When we click on the Continue button, the installer will ask to ‘Read Licence’.  It also shows two-buttons-- Disagree and Agree.To install the Node.js we need to click on Agree.To proceed further we need to specify the Login password to continue the installation.In the below screenshot the user has administrative rights for software installation. So, the admin needs to type the password in order to proceed further.After clicking on the Install Software button, click on the Install button.In the next screen, the progress bar will indicate the installation progress.Post-installation, it will provide us with a summary as below.After closing this window by clicking on the close button, we need to verify whether we have installed the said version of Node.jsTo open command terminal, press Command + Space barThis will open Spotlight search as below.We need to type Terminal and hit enter.Once the terminal is visible, we need to type the following commandnode - vAs we can see it is showing us the node version (v14.15.1) as in the screenshot.So, we have installed Node version 14. Each build is denoted by semantic versioning. The first digit, in this case, is 14, which represents a major release. The second digit represents new features with the release and the third digit represents patch and bug fixes as associated with the major release.Node.js installation by command line.As an alternative method, we can install node.js by the terminal as well. But as a prerequisite, we need to have homebrew (https://docs.brew.sh/Installation)  in MacOS.We are assuming, we have homebrew installed in our system.And to proceed with the command-line installation, we need to open the terminal and type the following command.brew - vThe above command will inform us about the homebrew version.To update the brew, type the following commandbrew updateAfter the above command has been executed, we need to typebrew install nodeThe installation will take some time, so give some time to the system and be patient.To verify the Node.js installation usenode -vTo verify the npm installation usenpm -vCongratulations, we have installed Node.js and NPM.5. Create-react-app for react app on macOSNow, we are going to install create-react-app on macOS.Create-react-app is a quick way to set up a single page application code with minimal steps and no configuration.Let’s proceed with the installation steps.Please type the following command in the terminal to create a folder with the name react-app. mkdir react-appThen navigate to directory react-app as follows:cd react-appTo verify directory, type command and enter as belowpwdOnce we have confirmed that we are in the right directory type below command.npx create-react-app my-appnpx is a module which is included with npm.The installation steps as shown in the above screenshot will take some time.So, sit back and relax.Once the above command has been executed successfully....….navigate to my-app directorycd  my-appAnd typenpm startWhen the command is executed successfully, it will open the browser at localhost:3000 in the browser.And we can give ourselves a pat on back for the small win!6. Download and Install React (Explicit command)This step is for awareness only.In the previous step, we have not explicitly installed React.js as this is installed with the help of create-react-app package.We can also install the React.js  by using the following command.  And we may need to install the module dependencies on our own.npm install react --save7. File folder and structureWe can see that we have not touched the codebase but found the minimal single page web application running on our macOS.To see the code structure, we need to open the code editor e.g. Sublime, Atom etc.And open the folder my-appAs we can see, there are various folders and at a high level there are below folders:node_modules public srcIn the public folder, we can see index.html. This is the page template.The index.js in src folder is the JavaScript entry point.The app is displaying the code from the App.js in the src folder.In the my-app folder, the package.json is an important file which mentions the app name and module dependencies. Feel free to explore further.8. Summary (conclusion)In this tutorial, we have learnt about React.js, and the component-based architecture model in React.js. We also had a high-level overview of the virtual DOM.We touched on the concept of reconciliation, the usage of Node.js in the world of JavaScript and its capability to handle non-blocking I/O output to fulfil client connection requests simultaneously.We have checked two methods for Node.js installation, namely with the package manager and another one by using the command line.To install React.js, we have relied on the create-react-app module for a quick start. We can also install the React.js by command line. To prevent being overwhelmed with too many details we have picked the create-react-app method for this tutorial. We created our first react app and saw it running.To become familiar with the code in terms of development perspective, we quickly checked the important files which are running the app.
3486
Installation of React on Mac

Hello learners! In this tutorial we are going to l... Read More

Standups for agile teams

Communication is the key for any team working closely to deliver a solution. The foundation of Agile is based on frequent interactions that provide multiple opportunities for the team to come closer, daily standup being one of them. There may be varied names for daily standup like daily scrum, daily huddle, quick catchups, daily sync-ups, etc. but the purpose remains unchanged. Going back to the non-agile days or to the teams which are not working in an agile fashion, they too, choose a time to interact, to update, or to check on any new advancements, but, the frequency differs. So, what makes daily scrum different from others? What is a Daily standup scrum ceremony? The daily standup is one of the scrum ceremonies prescribed by Scrum, where the team meets daily; same time, same place, to talk about Sprint goals and also check if they're on track or if there's a need to change the course. Daily Scrum helps the team to track the progress, for which they use the Sprint board. The Sprint board is essentially used to talk about the deliverables, the associated timelines and if there's any impediment that is stopping them from moving forward. The daily standup meeting is not a status update meeting; it is a time when the scrum team collectively discusses and takes ownership for a Sprint goal.  The term ‘standup’ is used because it is meant to be short and precise. It is usually done with team members standing up to discuss the work items, though this is not compulsory. The purpose of standing up is to keep the meeting short and to the point. Daily standup, in a way, provides daily planning for the scrum teams to stay focused on the sprint goal. How to conduct a Daily standup To conduct a good daily standup, everyone in the team should be aware of the agenda and come prepared for the discussion. The scrum master initiates the meeting with a quick warm-up topic (hardly lasts for a minute) that sets the tone for the meeting and serves as the ice breaker. It can be anything general; from the weather to appreciation, or any topic that makes the team comfortable.  For the entire meeting, the team remains focused and involved. They can stand near the Sprint board or any visual board where they're tracking the progress. In case of a distributed environment, the team should be using the screen share with the details of the sprint board/taskboard. 'Three questions' - the core of Daily Standup: What I did yesterday? What is my plan for today? Or before we meet again. Are there any impediments? Time-boxing the daily scrum meeting is vital; it should not go beyond 15 minutes. If there's anything the team wants to talk about apart from 'three' questions, it should be done once the daily scrum is over. Any discussion on the impediment that doesn't require the complete team should be taken as a sidebar.  Everyone in the team gets a chance to talk about the task/work in hand. As a rule, when a team member is providing the inputs, the other members will listen and stay quiet. This ensures that only one person is talking at a time. The scrum master can introduce creative ways of conducting a daily scrum that helps team participation and induces respect for others.  Here’s an example of how team members can respond to the three questions: “Yesterday, I completed writing the test cases for the login screen.” “Today, I will work with John to get it peer-reviewed and will also start testing the authentication part” “No blockers” Swift and short. Sticking to three questions helps in completing the daily scrum on time. Staying with the rules promotes discipline and better work culture.Why is the daily standup important? Transparency and planning are vital for effective delivery. Getting teams on the same platform requires collaboration, communication, and teamwork. Daily scrum provides the team with the opportunity to talk about the daily task, communicate any blockers, and discuss if there's any change in the plan. A short 15-minute sync up helps the team stay focused on the goal. The team members can call out if they need any help with the work items, which is another opportunity to take ownership as a team.  Some of the benefits of a daily standup include: Improves communication Helps to identify blockages or impediments An opportunity to inspect and adapt Improves team accord Helps to keep the team focused Increases the level of accountability  Creates a sense of accomplishment while talking about the done tasks Though it has many benefits, it can only be reaped if the daily scrum is done in a way prescribed in the Scrum Guide. Daily scrum is one among the five key events to be conducted in a sprint and serves a tactful purpose. For most of the teams, daily scrum is one of the first things that happens at the start of the day. It sets the tone and the expectation for the entire day, similar to creating a to-do list before the start of any work.  Who Attends a Stand-up? The daily scrum is one of the scrum ceremonies that is attended by the development team, the scrum master, and the product owner. Anyone else apart from these three roles can join but they'll have to be quiet and stay as an observer till the time meeting gets over. At times people from different areas who are directly/indirectly involved in the delivery may want to check on the progress. They can be a part of the daily scrum, but the rule applies to them as well, which is, only the scrum team will talk. They can ask questions only when the daily scrum is over. What do we talk about? The format of the daily scrum sticks to the three questions: What I accomplished yesterday? What is the plan for today? Are there any impediments in the path of my work? These three questions help the team to stay focused and timeboxed.  With the first question, the team member will talk about what they have completed before the start of the daily scrum. It consists of the task that they had planned and called out in the last daily scrum. Sometimes there might be a certain deviation from what they had mentioned and what exactly they worked on. This should be called out specifically as part of the daily scrum. Talking about the ‘done’ work creates a sense of accomplishment and sets the right tone for starting up with another task. The second question is more about the plan for today or the plan once the daily scrum is over. Here the team member talks about the work items they plan to finish before the next meeting. It is advised to pull only as per the capacity. While answering this question, there might be a need to change the course of action in case there's a dependency or if there's any impediment that blocks the way forward for that task. When the team member is calling out the items they have planned to work on, it creates a sense of ownership as they announce the strategy. The third question focuses on clearing the path and removing any impediments that might come in the way of delivery. The team member raises any impediment or blockages they foresee, or they talk about the blockers that can impact sprint goal. Talking about the impediments helps the team to readjust the course and look for ways to resolve the blocker as early as possible. Identifying blockers early helps to reduce the risk.  Where and when? The daily standup should happen at the same time and same place. Finding a new place every day creates an overhead and it is time-consuming, hence the reason for ‘same place’. The scrum team should use the sprint board to call out the task and the subsequent progress. Ideally, the daily scrum should happen near the Sprint board. This helps in visualizing the flow and to realize where the team stands in terms of the Sprint goal. Setting up the sprint meeting at the same place daily helps in wiring the minds of the team member to follow the same discipline. If the team is sitting alongside several other teams, it might create a noisy environment to run the daily scrum. In such instances, the scrum master or any of the team members can book a meeting room on a recurring basis.  To address the ‘when’ part, the meeting should ideally be the first thing to be done when work starts. Being the first team activity, it helps in planning the entire day which further creates momentum amongst the team members. The start time must remain consistent and one should avoid rescheduling the daily scrum. With flexible work environments, it might not be possible that everyone is present at the same time during the start of the day. In such cases the team should opt for a slot where they can have maximum participation. Working across time zones requires a slot that works for all. The daily standup should not be treated as a kickoff for the day, but as a time to talk about the advancement towards the goal and the issues and any help required with them. Keeping the meetings timeboxed and on time helps the team to create a disciplined work environment. Daily scrum gives an opportunity to self-organize and work as a team towards a single goal. Stand-ups for distributed teamsWith the worldwide pandemic situation and the teams working from home, we are living in a world with an extremely distributed environment. Agile helps here too. In such cases, the teams should be leveraging the online tools available, such as Zoom, Microsoft Teams, etc. for video conferencing. The calendars should be updated with the recurring meeting invites that consist of a link to join the video.  Why focus on video? Because humans feel more connected through video calls rather than just audio. Also, video conferencing promotes collaboration and creates a sense of a safe environment. Common Downsides to look for: Impediments are not getting raised – There can be multiple reasons for blockers not being shared across the team. Trust issues can be one of them. The Scrum Master/facilitator should help the team feel safe and provide the team with a platform to voice out the issues. Team Members reluctant to join – In some cases, the team members might feel the daily scrum to be a useless activity or it's just another meeting. In such cases, the facilitator should try to understand the reason behind such behavior and coach the individuals on the benefits. Daily Scrum gets converted to the status meeting – There are subtle signals to watch out for. Timebox not being followed. Conclusion If you want the Scrum implementation to work for your team, following the prescribed practices and ceremonies helps a great deal. Even more than the process or ceremony, it is important to understand the team and how to make them energized to start the day, you should also learn how to best leverage the scrum ceremonies to get the best benefits and improve the overall productivity and teamwork. Daily standups help to focus on the common goal and raise the overall morale of the team and project.  
9257
Standups for agile teams

Communication is the key for any team working clos... Read More

What is the Use of Axios in React?

While dealing with web applications in React, the most common task is to communicate with backend servers. This is usually done via HTTP protocol.  We are all quite familiar with the very common XML Http Request interface and Fetch API, which allows us to fetch data and make HTTP requests. There is another way to communicate with the backend in React, and in this article we will learn about the awesome library known as Axios and some of the key features of Axios  that have contributed to its popularity among frontend developers. So let’s get started.What is Axios? (A little bit of history) Axios is used to communicate with the backend and it also supports the Promise API that is native to JS ES6.  It is a library which is used to make requests to an API, return data from the API, and then do things with that data in our React application. Axios is a very popular (over 78k stars on Github) HTTP client, which allows us to make HTTP  requests from the browser. Why Do We Need Axios in React? Axios allows us to communicate with APIs easily in our React apps. Though this can also be achieved by other methods like fetch or AJAX, Axios can provide a little more functionality that goes a long way with applications that use React.  Axios is a promise-based library used with Node.js and your browser to make asynchronous JavaScript HTTP requests. When we know we need to implement some promise-based asynchronous HTTP requests in our application, with JavaScript, we usually think of only jQuery’s AJAX or fetch method to get the job done. And while doing so, we are actually going against React!! Did you notice that? So, while React doesn’t care about DOM manipulation at all, why do we need jQuery for our React app? Since React is handling each and everything within its own virtual DOM, perhaps we don’t need  jQuery at all. And hence, Axios becomes a lighter-weight/optimized solution to play around with our HTTP requests. Apart from the above mentioned points, why I personally like AXIOS is because it has a very clean and precise syntax. See  the example code below: Don't worry if you are not familiar with the code, we will learn that later. Using FETCH API:   const getPostsData = () => {   fetch(‘https://jsonplaceholder.typicode.com/posts’)   .then(response => response.json())   .then(data => console.log(data))   .catch(error => console.log(error));   } }  getPostsData();Using AXIOS: const getPostsData = () => {   axios   .get("https://jsonplaceholder.typicode.com/posts")   .then(data => console.log(data.data))   .catch(error => console.log(error));   };  getPostsData();You might be thinking that there isn’t a very big difference but if we consider a POST or Delete or PUT request you can start observing the benefits of using Axios.  Prerequisites In order to use Axios with React, you’ll need the following: Install Node (v 10.7 or above). And if it is already installed, check the version by using npm -v  A React project setup with Create React App or any React boilerplate If you want to learn more about Axios library, head up to this link https://github.com/axios/axios.  Okay, now that we have spent a good amount of time in understanding Axios, let’s turn our attention on how to use Axios with React. Installing Axios In order to use Axios with React, we need to install Axios. It does not come as a native JavaScript API, so that's why we have to manually import into our project. There are many ways to install Axios. You can pick any of them based on your system environment. Open up a new terminal window, move to your project’s root directory, and run any of the following commands to add Axios to your project. Using npm: $ npm install axios  Using bower package manager: $ bower install axios  Using yarn:  $ yarn add axios  Using unpkg CDN:     Using jsDelivr CDN:      It’s not as complicated as you  might think it’d be.  Fetching and Consuming Data with a Axios (GET-POST-DELETE) Web Applications use HTTP requests, for example, GET, POST and PUT, to communicate with APIs. Axios makes our life simple as it is easy for us now to perform these commands. In this section, we will learn how to use the Axios to make REST API calls like GET, POST  and DELETE in React App. So let’s get started. Performing GET Request with Axios Let’s create a new component named My List and hook it into the component DidMount lifecycle as shown below. After that we will fetch data with Get request by importing axios. Here we are using JSON placeholder API for fetching the dummy list data of users. import React from 'react';  import axios from 'axios';  export default class MyList extends React.Component {   state = {   persons: []   }  componentDidMount() {   axios.get(`https://jsonplaceholder.typicode.com/users`)   .then(response => { const users = response.data;   this.setState ({users});   })   }  render() {   return (   < ul >   {this.state.users.map (user => {user.name} )}   < /ul >   )   }  }In the above component named MyList, we have imported Axios first. axios.get(--URL--) is used to get a promise which will return a response object. The received data in response.data is assigned to the user's object.  We can also retrieve other Information like status code and others received with the response. Performing POST Request with Axios Now let’s create another component named AddUser for using the POST request which will add a user in the user list. (a.ka. Adding data into database) import React from 'react'; import axios from 'axios'; export default class AddUser extends React.Component {  state = {  userName: '',  }  handleChange = event => {  this.setState({ userName: event.target.value });  }  handleSubmit = event => {  event.preventDefault();  const user = {  userName: this.state.userName  };  axios.post(`https://jsonplaceholder.typicode.com/users`, { user })  .then(res => {  console.log(res);  console.log(res.data);  })[Text Wrapping Break] }  render() {  return (        User Name:      Add      )  }  }In the above example, we have made a HTTP Post request to modify the database, which is a user list and added a new user to the database. Because we've initialized the state, in handleChange() we have updated the state when the API request returns data successfully. Performing POST Request with Axios Finally, the delete method. axios.delete is used to make a Delete request to the server. axiox.delete accepts two parameters: url and optional config.  axios.delete(url, { data: { foo: "bar" }, headers: { "Authorization": "***" } }); We can use config.data to set the request body and headers as shown in the below snippet. Consider the same component as above and modify the request as follows: handleSubmit = event => {   event.preventDefault();   axios.delete(`https://jsonplaceholder.typicode.com/users/${this.state.userName}`)   .then(res => {   console.log(res);   console.log(res.data);   })  } And you are done! — you’ve got a transformed and simplified React appSending custom headers with Axios Sending custom headers with Axios is very simple and straightforward.  It is done by passing an object containing the headers as the last argument.  See the below code reference:  const options = {   headers: {'X-Custom-Header': 'value'}  };  axios.post('/save', { a: 50 }, options);Looking at the response object When we send a request to server and it is successful, our then() callback will receive a response object which can have the following properties: data: It is the payload returned from the server. By default, Axios expects JSON and will parse this back into a JavaScript object for you. status: It is basically the HTTP code returned from the server. statusText: it refers to the HTTP status message returned by the server. headers: It contains all the headers sent back by the server. config: It has the original request configuration. request: It is the actual XMLHttpRequest object (when it is running in a browser)Looking at the error object And if there’s a problem with the request, the promise will be rejected with an error object containing at least one or few of the following properties: message: the error message text. response: the response object (if received) as described in the previous section. request: the actual XMLHttpRequest object (when running in a browser). config: the original request configuration. Features of Axios Library as per the Documentation: Automatically transforms for JSON data Axios is intelligent because it automatically converts a response to JSON, so while using Axios we usually skip the step of converting the response to JSON, unlike we do in Fetch() Transform request and response data Make HTTP requests from Node.js Make XMLHttpRequests from the browser Client-side support for protecting against XSRF Supports the Promise API Intercept request and response: HTTP interceptors are used when we need to change HTTP requests from our application to the server. Axios provides a way to intercept HTTP requests.  And hence Interceptors provide us the ability to do that without writing any extra code. Has an ability to cancel requests It has a built-in feature that provides client-side protection against cross-site request forgery. In case you want to dig in and learn more about these features, head up to the official documentation of AXIOS. MAKING MULTIPLE REQUESTS WITH AXIOS With Axios we get an ability to make multiple HTTP requests and handle them simultaneously using the axios.all() method. This method takes in an array of arguments and in return we get a single promise object that only resolves when all the arguments passed in the array have been resolved. Look at the below example, where we are making multiple requests to the GitHub api using the axios.all() method. axios.all([   axios.get('https://api.github.com/users/defunkt),   axios.get('https://api.github.com/users/evanphx)  ])  .then(response => {   console.log('Date created: ', response[0].data.created_at);   console.log('Date created: ', response[1].data.created_at);  }); What will happen in the above code is that it will make simultaneous requests to an array of arguments in parallel, return the response data and will console the created_at object from each of the API responses.  Think About Abstraction  In Axios it’s quite possible to create a base instance where we can drop the URL for our API as shown below:   const api = axios.create({ baseURL: "https://api.github.com/users/evanphx" });And then simply abstract the URL like shown:  async getPostsData() { const response = await api.get();   try {   this.setState({   posts: response.data.posts,   isLoading: false   });   } catch (error) {   this.setState({ error, isLoading: false });   }  }Shorthand Methods in Axios  You have already seen that Axios provides an easy-to-use API contract model in a compact package for most of our HTTP communication needs. Do you know that Axios has some shorthand methods for performing different HTTP requests?  Check them below:  axios.request(config) axios.get(url[, config]) axios.delete(url[, config]) axios.head(url[, config]) axios.options(url[, config]) axios.post(url[, data[, config]]) axios.put(url[, data[, config]]) axios.patch(url[, data[, config]]) Some Awesome Facts about Axios  Wondering about some cool facts about Axios? Let’s check them out! For Axios, there is no need for a browser environment. This neat simple library also works on the server-side!  And hence we can use Axios in our Node applications as well. Apart from fetching or retrieving data, with the help of Axios we can also check the token expiry while requesting data for client-side and server-side. And when the token is already expired we can call an API to get the new token and continue the previous API request.  In Axios, monitoring the upload and download progress is quite simple. How? Just set a callback in the request config as shown below, and enjoy. axios({   method: "get",   url: "/myFilePath",   responseType: "blob",   onDownloadProgress: (progressEvent) => { const percentCompleted = Math.round(   (progressEvent.loaded * 100) / progressEvent.total   );  console.log(percentCompleted)   this.setState({   loadingPercent: percentCompleted,   });   },  }).then((response) => {   alert("We are Ready!");  });Conclusion I hope this article has helped you in understanding about Axios and its usage for various features like fetching or retrieving data and handling responses.  In this article, we saw several practical examples to check the power of Axios inside a React application to create HTTP requests and handle responses. We also got an idea about why it is a better approach than a normal fetch api.  So what are you waiting for? Go ahead and give Axios a try. It will definitely make your life easier. Happy Learning.
5646
What is the Use of Axios in React?

While dealing with web applications in React, the... Read More

Install And Setup React App on Ubuntu

React is a JavaScript library for building user interfaces. It is opensource and maintained by Facebook.You can read more about React here:  https://reactjs.org/docs/getting-started.htmlIn this blog we are going to learn how to install and setup a React App on Ubuntu (version 16 and above).PrerequisitesThis blog assumes that you are using Ubuntu 16 or above versions and you have all the privileges to install the software in the machine, and also have access to the required websites mentioned in the blog.System Requirements:Ubuntu 16 or aboveMinimum 4GB RAMVisual Studio Code installed.Why should we choose React, and what are its advantages?React is built on JavaScript which makes it easier to learn and easier to use.React is component based which means we can write re-usable components. Start with small things, which you use to build bigger things, which you use to build apps.React is lightweight compared to Angular; which in turn makes your application faster to load—which is very important from the user’s point of view.React ensures faster rendering of DOM (document object model), this has been achieved by the introduction of Virtual DOM-currently, one of the benefits of using React for heavy loaded and dynamic software solutions.React has a helpful and interactive developer toolset which makes it easy to debug. React Developer Tools is a browser extension available for both Chrome and Firefox. It enables developers to observe reactive component hierarchies, discover child and parent components, and inspect their current state and props.  React uses JSX(JavaScript XML) which has HTML-like syntax, making it easy to code and understand.React has strong community support on Github, Stackoverflow and many other platforms.React is SEO friendly.There are certainly many other nice features about using React.What is Node.js?Node.js is a JavaScript runtime built on Chrome's V8 JavaScript engine. Node.js is an Open Source Server Environment that is free and runs on almost all Operating Systems (Windows, Linux, Unix, Mac OS X, etc.).You can read more about Nodejs here: https://nodejs.org/en/Why do we need Nodejs for React apps?Node.js lets developers use JavaScript to develop variety of applications like network applications, command line tools, web APIs, mobile applications, web applications etc.React usually runs on Node Server in development, but we can make use of other Servers likes Apache or Nginix to run React App in production. You do not need NodeJS to run React in production.What is NPM, why do we need NPM for React apps?NPM (Node Package Manager) is a dependency management tool for JavaScript applications. It is Open Source and also has command line utility for interacting with the application that aids in package installation, version management, and dependency management.React does not ship with all the features by itself, so it uses external packages to add the required features to the React application. These packages are maintained by NPM (Node package manager) which is shipped with Nodejs in development.You can read more about npm here: https://nodejs.org/en/knowledge/getting-started/npm/what-is-npm/We can use yarn instead of NPM during development and production for React apps.Install Node.jsThere are many ways to install Node.js in an Ubuntu machine.Install Node.js from the Ubuntu repositoryInstall Using a PPA (personal package archive)Using the first method we will not get the latest version of Node.js installed so we will choose the second method where we will get the latest version of Node.js installed.Installing Using a PPA (personal package archive)To get the latest version of Node.js installed on ubuntu, add a PPA (personal package archive). It is maintained by NodeSource.Open terminal and run below commands:Install curl: Run below command on terminalCommand: sudo apt-get install curlSet the NodeSource PPA: Run below command on terminalCommand: curl -sL https://deb.nodesource.com/setup_current.x | sudo -E bash –The PPA will be added to your configuration and your local package cache will be updated automatically.You can read more about available versions of Node.js in nodesource here: https://github.com/nodesource/distributions#debInstall Node.js: Run the below command on terminalCommand: sudo apt-get install -y nodejsCheck for Node.js Installation: Run below command on terminalCommand: node -vIt has to show the version of node installed in this case v15.4.0Now let's see how we can install and setup React app in Ubuntu machineUsing create-react-app (installing create-react-app using npm)Using npx (Recommended in React docs)Using create-react-app (npm)In setting up a React project we come across tools like babel and webpack which are not easy to understand and configure for a person who is new to React and JavaScript. There are several tools that help to sort this problem. One of them is create-react-app. This is the easiest to setup. Create-react-app comes with production grade configurations pre-built. You can alter the configurations by ejecting from the create-react-app as well.Follow the below steps to install using npm create-react-appGo into your desired location where you want to start your react app using ‘cd’ command Run below command to install create-react-app using npm Command: npm install -g create-react-appNow Run create-react-app on terminal to setup a React-app. Command: create-react-app hello-worldThis creates a folder with the name hello-world. You can navigate into the folder using ‘cd’ command and look at the project structure.This gives the React app which we can use, but React recommends using npx.Using npx command:npx is the package runner, since npm version 5.2.0 npx is pre-bundled with npm.Read more about differences npx and npm here: https://www.freecodecamp.org/news/npm-vs-npx-whats-the-difference/Follow the below steps to setup using npx.Go into your desired location where you want to start your react app using ‘cd’ commandRun the below command to setup React app using npxCommand: npx create-react-app my-appThat’s it! Your React app is ready with a single command.This creates a folder with the name hello-world. You can navigate into the folder using ‘cd’ command.  Now open the project in vs-codeWhen you open the project in visual studio code the structure looks like this.Now let's have a look at the files and folders we have:node_modules: This folder is managed by package manager (npm) and contains all the project library dependencies. We should not edit any file inside this folder.public: This folder contains the assets that should be served publicly without any restrictions and contains files like index.html, favicon, manifest.jsonsrc:  This is the folder that contains all the files that are used to create web applications. As a react developer you are likely to spend a lot of time in this folder creating components and other sources of code..gitignore: This file has all the assets which should be ignored by git while we publish our code to GitHub eg: node_modulespackage.json: This is a JSON file which has all information about the app such as name, dependencies, scripts we use to run the application etc.Readme.md: This is a markdown file where you specify the things which you want to show when someone visits your project on GitHub.Now let's run our first React app!Open the terminal integrated with Visual studio code or just stay in the ubuntu terminal; either is fine. Let's use the integrated terminal.Run the app using the following command: Command: npm startThis opens the app in your favourite browser as shown below:Now, let's make our first code changes:On navigating to src folder, you will find App.js file, through which the whole app is run inside the browser. Change the code as you see below and save by hitting ctrl+s.Now look at the browser where the app is running. It looks like the one in the image below.Congratulations on making your first React app!What you have learnt:What is React and why it should be usedWhat is Node.js, and how it should be installed on Ubuntu.What is npmWhat is create-react-appHow to setup React-app on UbuntuHow to run the React-app  How to make code changes to create your first React application.React has rapid changes for every new version. It is important to keep yourself updated with the latest releases of React, so that you can make your life as a React developer easier!
2313
Install And Setup React App on Ubuntu

React is a JavaScript library for building user in... Read More

Instal React Js on Windows

IntroductionIn this tutorial, we will learn how to install React.js on Windows.React.js is a library which helps us to build and create front end interfaces for Single page applications and it utilises the power of virtual DOM.React.js was an inhouse project of Facebook, and it was made open to the public in the year 2013. The adoption of React.js has seen an upward curve since its avantages have been realized. Various startups and established organizations are now adopting the technology and upgrading their technology stack.1. Prerequisite for WindowsTo install React on Windows, your system will require the minimum configuration as below:Windows XP, Windows 7 (32/64 bit) or higherMinimum 4 GB RAM and higher10 GB available space on the hard diskAt least one Internet Browser e.g. Chrome, Firefox, Microsoft Edge etc.Node.jsActive internet connection minimum speed 512kbps and above.At least one installed code Editor to test and debug your code e.g.  Atom https://atom.io/Sublime https://www.sublimetext.com/Visual studio code https://code.visualstudio.com/download.2. Introduction to React.jsReact.js is a library written in TypeScript. It utilises the syntax of the modern version of JavaScript as described by ES6 and its higher version.Applications built using React.js use the Single reusability principle. This advocates the idea of building web pages and applications using components and unidirectional flow. In React.js we have the concept of states and the concept of immutability. Components have hierarchy in terms of Parent and Child components. A component in case of React.js can be thought of as a piece of code which is based on the principle of pure functions. We will look into the pure component later. First, let’s understand what a state is. For e.g. To become a member of a service, the user fills his information on the registration page. While filling the details there can be many states of the form, for e.g. When the form field is empty or when the form field has witnessed some error on some particular field, which needs to be corrected; or when after correction, the form data has been validated and is ready for submission. So, at a broad level, the registration form has been through various states. These states represent at which level the application is, in terms of interacting with the end-user. Each level of interaction for this form is represented by the state, from an empty form to being a fully filled form with a display of an error for certain fields and the validated form. In React.js, we have the component based on the pure function. A pure function can be memorised as a piece of code, which does one task and does it pretty well. For a certain input, it always returns the same output, so this means we are increasing predictability of the code. Since React.js follows a certain code pattern and principles in order to work, it lowers the curve of the knowledge gap; whether you are one-person or a team of developers working mutually.3. Introduction to Node.js and NPM on WindowsTo run React.js we will require Node.js on our system.Node.js is a server which will help us to run the React.js code.It is based on non-blocking input and output and the Chrome V8 JavaScript engine. The Node.js code is open source.NPM which is an abbreviation of Node package manager, npmjs.com is supported by various developers around the world. It has various node modules, using which developers can host and publish their modules on the open-source community.  It hosts modules in private and public visibility.A module carries code which exists to serve high or low level functionalities. In terms of code adoption and availability of various modules it gives an edge and tries to make the developer more productive.  We can plug in and plug out the module. Some modules are dependent on other modules; which is defined as dependency among modules.While building an application, a developer can pick the module, tweak and remix it to suit the application needs, and can then release to the open-source community. So, instead of reinventing the wheel, it is like picking a wheel (npm module) from npmjs.com, giving it further momentum and giving it back to the open source community.4. Download and Install Node.jsTo install Node.js we need to go to the URL https://nodejs.orgDepending upon our Windows OS version in terms of 32 Bit or 64 Bit, we can pick the installer and install that version.  In this tutorial I am using Windows 8, 64 Bit.  The Node.js installer includes NPM. It is best to install the even numbered version of NPM.Depending upon your operating system, the Nodejs.org home page will show the Download button and recommended LTS version.After the download is complete we will go to the downloads folder and run the installer.The installer will show the below Setup Wizard. Click next.The next screen will ask for the End-user License Agreement. Select the checkbox at the bottom right to provide your consent and click on Next to proceed with the installation.The installer will ask for Destination folder and the default path set by installation is C:\Program Files\nodejs\Click on Next buttonThe above screen is an important step in the installation process. And if you see closely it also sets the environmental path variables to command prompt on Windows.Click on Next to continue with the installation.The Windows OS may ask you to allow Node.js installation and make changes.Click on Yes button.During the installation, if you have allowed for Chocolatey and required modules installation for C++ and Python, you will see the UI below in the command prompt. This installation requires 3 Gb of free disk space. In this tutorial this step is not required, so we are skipping this step by closing the window.If you are interested in installing it, press Enter to continue.Once the istallation is complete you need to verify the Node.js installation.  For this we will use the command prompt.To run command promptPress keys Win+RAnd type cmd in the window below.Next Click on Ok or Press Enter on the keyboard.5. Installation of ReactAfter installation of Node.js we need to install React.To check the Node.js version, open the Windows command prompt. Press Win+R and type cmd. In the command line, type   node -v to see its version. We can also check for npm version, which is installed with Node.js, with the following command npm -v After running these commands, we can check the node version v14.15.1 and npm version 6.14.8As we have confirmed the Node.js installation we can proceed to the next steps.While in the command prompt, we have navigated to a folder called Codefactory by following the command cd CodefactoryIn this folder we have created a folder  called react-windows by using the command mkdir react-windows.After the folder react-windows has been created, we will change the directory to react-windows with the command cd react-windows React.js can be installed in various ways. Now, we will type npm init. It will ask for the below configuration line by line. Insert your input, followed by Enter keypress to proceed with the next configuration.   At the end of the configuration it will confirm for the inputs you have entered. If you are happy with the configuration data, type yes and enter to continue.The npm init will help us to create a package.json file.Now, the next step to install React.js requires us to go to the command prompt and type the following command in the react-windows directory.npm install --save reactAnd after the above command npm install --save react-domBehind the scene, these commands fetch the specified module from npmjs.com and download it in the local codebase.Let's have a look at the react-windows folder. Here we can see some newly created directories in node_modules.So, in this tutorial, we have learned to install React and reactDOM. But to see the React.js SPA (single page app) there is more work to be done in the above code.As an alternative and fast approach we can do it via create-react-appLet us move to Codefactory folder and with the command cd.. create another folder react-cliNext, type the following command mkdir react-cliNow we will use create-react-app module and type the following commandPlease note that my-fast-app is the name of your app. This is an example and you can be creative in choosing your own name.npx create-react-app my-fast-appIf we see closely it will take care of the rest of the installation steps, and react, react-dom and other related modules are installed automatically.This process is a little data intensive, so please be patient while the download and installation happensWhen the above step gets completed the command prompt displays the below output.Now, let us run our first react app, by navigating to my-fast-app directory as belowcd my-fast-appAnd enter the next command as npm startThe npm command will show the application in the browser. http://localhost:3000And if you are running node.js for the first time using npm command, it will ask for permission to allow access and we need to allow access to run.As we are using a code editor we can have a look at the directory structure and some of the important files, such as index.html in the public folder, in src folder the index.js and App.js. The src folder contains the react component which we can build further on this codebase. index.js is the js invocation point for react app.This index.js is linked with the App.js, which is responsible for showing the content in the browser. That’s what we see on the demo page.Let’s edit the App.js by going to line 10 and adding the following codeTalk is cheap, show me the CodeOnce you save the file by Ctrl+SThe code will be auto refreshed in the browser, after compiling.It will show us the following output.So, now feel free to change messages and alter the page layout and structure for  experimentation.If you are familiar with CSS, you may also change the page style using App.css and tinker with the code as well.SummaryIn this tutorial, we have introduced you to React.js . Its impact in terms of building modern front end interfaces using component-based architecture is significant. We have also touched upon the concept of states, immutability and pure functions.We have got a brief introduction to the Node.js server and NPM modules, the capabilities of Node.js server and the power of the open source community in the npmjs.com.To install React, Node.js installation is a prerequisite.There are various methods for installation. Once we have installed Node.js, React can be installed either by npm commands or by using the create-react-app module.
4504
Instal React Js on Windows

IntroductionIn this tutorial, we will learn how to... Read More

Understanding the React useReducer Hook

IntroductionThe introduction of Hooks in React brought up a new way of writing and thinking about React applications. One of the most popular Hooks among developers so far is useReducer, which allows us to handle some complex state manipulations and updates, and this is what we’ll be learning about in this article.In React there are two main hooks that are used for state management, and we all know them. These are:useState, anduseReducerYou might have heard or used React.useState hook, and if not you can directly read React’s official documentation about Hooks here.Have you ever found any difficulty in choosing a state management library to manage and handle a global state in a React app? Or, what if you need to manage more complicated data structures or perform any side effects?Thinking over these concepts is quite tricky and time-consuming.Well, this is pretty much what we are going to learn and cover in this article, so read on!  PrerequisitesIn order to get the full benefits of this article, I’d recommend you to double check this prerequisite list and set up the environment as suggested.Npm or Yarn installedNode.js version >= 12.x.x installedcreate-react-app cli installed or use npxBasics of React Hooks, (if not kindly read this first)What is a Reducer, anyway?What is the first thing that comes up in your mind when you hear the term reducer in React?For me, I am always reminded of JavaScript's Array.reducer() function.The only job of a reducer is to Reduce!We all know that the original reduce() method in JavaScript executes a given function for each value of an array  considering from left-to-right. And, here React.useReducer in fact, is like a mini Redux reducer.  A reducer is basically a function which determines a change to an application’s state. It takes the help of an action by using it to receive and determine that particular change.In react we have a lot of options, like Redux, that can help to manage the application’s state changes in a single store. Here we will learn about how we can make use of a reducer to manage shared state in an application.Reducer is one of the new custom Hooks introduced in React since v16.8. It allows you to update parts of your component’s state when certain actions are dispatched, and it is very similar to how Redux works.The reducer in ‘useReducer’ comes from Redux, which in turn borrowed it from JavaScript’s Array.reduce().It carries an initial state and a reducer function as its arguments and then provides a state variable and a dispatch function to enable us to update the state. If you’re familiar with how Redux updates the store through reducers and actions, then you already know how useReducer works. And if not, then also we will learn about useReducer functionality in core.So basically, what is useReducer Hook?The useReducer hook is used for complex state manipulations and state transitions.  Just like the other React hooks, we can import useReducer from react as shown in the below snippet:import React, { useReducer } from 'react';React.useReducer is a React hook function that accepts a reducer function, and an initial state.  const [state, dispatch] = useReducer(reducer, initialState);This hook function returns an array with 2 values. The first one is the state value, and the second value is the dispatch function which is further used to trigger an action with the help of array destructuring.  In the context of React, here’s what a typical useReducer pattern looks like:JSX:const reducer = function (currentState, action) { // Make a new state based on the current state and action return newState}const [state, dispatch] = useReducer(reducer, initialValue)// example usage: dispatch({type: "SOMETHING_HAPPENED"}) // Or with an optional "data": dispatch({type: "SOMETHING_HAPPENED", data: newData})Note: The “state” can be of  any kind. It doesn’t have to be an object always. It could be a number, or an array, or anything else.Pretty cool? Now let’s move further and understand how to use useReducer.How to use the useReducer Hook?Earlier we saw the basic useReducer which takes up two arguments: initial state and a reducer function. But useReducer hook actually takes up one more argument including reducer and initial state which is >>> a function to load the initial state lazily.This is usually helpful when we want the initial state to be different depending on some situation and instead of using our actual state, we could create the initial state anywhere, perhaps dynamically, and it will override the initial state.Syntax for the third argument is:const [state, dispatch] = useReducer(reducer, initialArgs, init); Let’s now understand step by step how to use useReducer and understand what’s happening behind the deck.Consider the following classic example of code to see the practical usage of useReducer:// Let’s begin to define the initial state of the component's state const initialState = { count: 0 } // Here is a function will determine how the state is updated function reducer(state, action) {  switch(action.type) { case 'INCREMENT': return { count: state.count + 1 } case 'DECREMENT': return { count: state.count - 1 } case 'REPLACE': return { count: action.newCount } case 'RESET': return { count: 0 } default: return state } } // Now inside our component, we can initialize the state like below const [state, dispatch] = useReducer(reducer, initialState);Explanation:In the above code snippet , we have  first defined an initial state for our componentadded a reducer function that updates that state depending on the action dispatched and,we have finally initialized the state for our component.Now as promised earlier, you don’t require an understanding of Redux to understand this concept. So let’s break down everything and see what’s happening.The initialState variableThis is the default value of our component’s state when it gets mounted for the first time inside the application.The reducer functionThe next step is to update the component’s state when some actions occur. This function tells what the state should contain depending on the action. It returns an object, which is then used to replace / change the state.It takes in two arguments which are a state and an action; wherein state is nothing but your application’s current state, and the action is an object which contains the details of all the actions currently happening.An action may typically look like this:const replaceAction = { type: 'REPLACE', newCount: 10, }It usually contains a type: which denotes what type of action it is. An action can also contain more than one data, which can also be the new value to be updated in the state.Dispatching an actionNow after understanding about the reducer and how it determines the next state for our component through actions, let’s see how actions are dispatched.Dispatch is just like a function which we can pass around to other components through props.You must have noticed that useReducer returns two values in an array. The first one is the state object, and the second one is a function called dispatch. This is what is used to dispatch an action.For example, if we want to dispatch replaceAction defined in the above example, we’d do something like this:dispatch(replaceAction) // or dispatch({ type: 'REPLACE', newCount: 10, })Summarising a bit here, hence for using useReducer we need the following:Defining an initial stateProviding a function which contains actions that can update the state.Trigger useReducer to dispatch the updated stateUnderstanding useReducer with examplesLet’s play with some real examples now to understand the concept better:Example:1 Simple Classic Counter ExampleLet’s imagine our Component is Counter. useReducer here in the below code accepts as arguments a reducer function, and an initial state value.  const Counter = () => { const [state, dispatch] = useReducer(reducer, 0)}In this case our state is an integer, which starts from 0:The reducer is a function that takes the current state and an action, which can be a value of any type you want. In this example it’s a string:const reducer = (state, action) => { switch (action) { case 'INCREMENT': return state + 1 case 'DECREMENT': return state - 1 default: throw new Error() } }We can use JSX to make this simple component work as below:const Counter = () => {const [count, dispatch] = useReducer(reducer, 0) return ( Counter: {count} dispatch('INCREMENT')}>+ dispatch('DECREMENT')}>- ) } This state can be an object with 'n’ number of properties, but different actions only change one property at a time.Putting up all this together, our Babel will look like:const { useReducer } = React const reducer = (state, action) => { switch (action) { case 'INCREMENT': return state + 1 case 'DECREMENT': return state - 1 default: throw new Error() } } const Counter = () => { const [count, dispatch] = useReducer(reducer, 0) return ( Counter: {count} dispatch('INCREMENT')}>+ dispatch('DECREMENT')}>-  ) } ReactDOM.render(, document.getElementById('app')) You should get the below output:Example2: Let’s see another TODO example. To show list of items:It was not possible to change the state of an item with the handler function earlier. But however, we can now do so, for example if we need to make the list of items stateful we can do so by using them as initial state for our useReducer hook by defining  reducer function:Consider the following JSX snippet for reducer:import React from 'react'; const initialTodo = [...]; const todoReducer = (state, action) => {  switch (action.type) { case 'DO_TODO':      return state.map(todo => { if (todo.id === action.id) { return { ...todo, complete: true }; } else { return todo; } }); case 'UNDO_TODO': return state.map(todo => { if (todo.id === action.id) { return { ...todo, complete: false }; } else { return todo; } }); default: return state; } }; const App = () => { const [todos, dispatch] = React.useReducer( todoReducer, initialTodo ); const handleChange = () => {}; return ( {todos.map(todo => ( ... ))} ); }; export default App; Now we can use the handler to dispatch an action for our reducer function.  Because we need the id as the identifier of a todo item in order to toggle it,  we can pass the item within the handler function by using a encapsulating arrow function as below:const handleChange = todo => { dispatch({ type: 'DO_TODO', id: todo.id }); }; And input will look like: handleChange(todo)} />Let's now implement to check our handler whether a todo item is completed or not by the below condition:const handleChange = todo => { dispatch({ type: todo.complete ? 'UNDO_TODO' : 'DO_TODO', id: todo.id, }); }; Putting up all this together, our component looks like:import React from 'react'; const initialTodo = [ { id: 'a', task: 'Do Something', complete: false,   }, { id: 'b', task: 'Walk over here', complete: false, }, ]; const todoReducer = (state, action) => { switch (action.type) { case 'DO_TODO': return state.map(todo => { if (todo.id === action.id) { return { ...todo, complete: true }; } else { return todo; } }); case 'UNDO_TODO': return state.map(todo => { if (todo.id === action.id) { return { ...todo, complete: false }; } else { return todo; } }); default: return state; } }; const App = () => { const [todos, dispatch] = React.useReducer( todoReducer, initialTodo ); const handleChange = todo => { dispatch({ type: todo.complete ? 'UNDO_TODO' : 'DO_TODO', id: todo.id, }); }; return ( {todos.map(todo => ( handleChange(todo)} /> {todo.task} ))} ); }; export default App; And here is the Output:Now the biggest question is:When do we use React.useReducer instead of React.useState? The answer is very simple and I will try to keep it even more simple:We can Use React.useReducer when -----Your application architecture is complex and big in size  When the logic to update state is super complex or you want to update state deep down in your component treeThe state value is either an object or an arrayYou need a more predictable, and maintainable state architecture of the applicationAnd, we can Use React.useState when -----Your application is smallThe state value is a primitive valueSimple UI state transitionsLogic is not complicated and can stay within one componentConclusionThe useReducer hook is a nice addition to the React library which allows for a  simpler, predictable and organized way to update our component’s state and makes sharing data between components a bit easier.It lets you optimize the performance of the components that trigger deep updates because now you can easily pass dispatch down instead of typical callbacks.And even if you take nothing else from this article, you should at least remember this: that useReducer allows us to define how we update our state value.Happy coding!
3490
Understanding the React useReducer Hook

IntroductionThe introduction of Hooks in React bro... Read More