Search

Step-by-Step: Create a React Project From Scratch

Hello learners. In this tutorial we will learn How to create a new React app. Before we begin, we need to understand few things. These tutorials are aimed for the aspiring and seasoned web developers & designer. If you are an aspiring web developer who wants to establish their career in React and other modern frontend technologies, these tutorials will provide you the basic understanding that you need to learn, rehearse and practice. And some additional links as a part of suggestive reading, which you can further dwell upon. As a lifelong learner, we need to be open to new ideas however they may challenge your beliefs at first.  Technology is a work in progress. It composes of sections of stable parts which can be applied to solve the problem of our lives. And some sections which are the part of debate and undergoing experimentation and transformation by the pioneers who forged & nurture the systems. The cutting-edge technology tends to follow approximately the following adoption curve.Source: Crossing the Chasm  (1990) -Author: Geoffrey Moore   Technology Adoption Lifecycle As you can see, the curve is divided among 5 sections as categorized by the work of: Innovators Early adopters Early majority Late majority  LaggardsArea under the curve represents number of customers  During the second phase, there is an important phase known as Chasm. Any nascent technology which becomes main stream must grow this phase with the help of Early adopters along with innovators. And every promising technology has gone through this phase before it has gained enough momentum and has gone mainstream. Before we learn React. We need to learn some concepts. And It will be good to have some basic understanding of how internet works. There are various technical jargon associated and it is a broad topic. If you are complete starter, I hope it will give you some base. We will try to understand and answer the following: What is Client & Server? What is meant by HTTP?Client & Server When a user is connected to the internet with the help of browser (Google Chrome, Mozilla Firefox, Internet Explorer, Safari & Opera). And when we type or do the google search with the help of keywords. We are presented a list of search results. The user computer is a client and google search engine act as server. As it serves to your queries in the form of the best matched results in a reasonable short time, it is good to say that the search results are produced at the blink of an eye. HTTPWorld wide web (W3C) is a consortium which governs the internet. It has set of rules and protocols which defines how the different machines can communicate over the internet. Sir Tim burner Lee is the inventor of the W3C.HTTP is a protocol, which tells and describe the transmission of hypermedia on the internet. It is designed based on the client server concept. In which one system is a client which seeks the information and other system is a server who act and fulfil the request of the client. In HTTP, there are various status codes for server, and it describes the status of server based on the client request.  Whether the request has been Successful any error conditions on Client & Server redirected by server & so on.1.a(1) HTML HTML is a mark-up language which is used to create hypermedia document on the internet. Hypermedia based documents are used to exchange information on the internet. HTML should not be confused with programming language such as C, C++, Java & C#. Let’s write a Hello World! HTML document as below: <!DOCTYPE html> <html lang="en">  <head>  <meta charset="UTF-8">  <title>HTML 5 Document</title>  </head>  <body>Hello World!</ body>  </html>To run the above code we can write it down or copy & paste in our favorite text editor and save it as Hello World.html. Please note .html is the file extension. And once we open the file with the browser it will show us the output as below.HTML is composed of various tags which defines the document and it's semantic. Semantic add meaning to the content as expressed by enclosing tags and it is not purely for visual presentation purpose.  The HTML 5 document begins with <!DOCTYPE html> HTML has also undergone various revisions and modifications. For e.g. If We need to present the information as paragraph.  Then we need to use < p > tag. For Tabular data < table >, Order list < ol > & unordered list < ul > and so on. References:Complete list of HTML references.HTML Standard & Draft list. 1.a(2)CSS Brief history CSS refers to the cascading style sheets. In the beginning year of the HTML, when HTML was used primarily to exchange information with the help of HTML document on the internet.   There was limited functionality to style the webpages. In fact, there were some tags which allows to style a page and change its formatting. But there was no separation of concerns, for e.g. the formatting tag and its associated attributes were often mixed with semantic HTML.And one of the early innovators Håkon Wium Lie recognized that there is a need of web page styling language which can address the presentation part of the webpages including the layout. And there is a need of separation of concerns.  Håkon Wium Lie along with the co-inventor Bert Bos had written the specification of CSS. < table> & its sibling tags were heavily used to structure the layout of the webpages. For E.g. To create multi column layout < table> were frequently used. It worked well to create the initial push to the web layouts, but it has own draw backs.  More on the history of CSSTo know more about how we can use CSS, we will start with previous code. To change the text color of Hello World! from black to green, we will declare a stylesheet called text.css. Naming convention for filename plays important rule, in recalling the file name when your source code becomes huge. It is good to start building on these habits. Hello World.html <!DOCTYPE html>  <html lang="en">  <head>  <meta charset="UTF-8">  <link rel="stylesheet" type="text/css" href="text.css" />  <title>HTML 5 Document</title>  </head>  <body>Hello World!</body>  </html>  Text.css body{  font-family: 'Arial', Helvetica, Verdana;  color: red;  font-weight: bold;  font-size: large;  }As you can see from the browser, it displays the Hello World! text in red color and font appearance is bold & larger. CSS has lots of modules which helps us to create sophisticated layouts, cool animations, image processing using css filters, accessibility (a11y) & much more. The current version of CSS is CSS3. As technology gradually evolved, so did the CSS.  It is maintained by CSS working group, which consists of invited experts and working group members.  If you are interested to explore more you may check some of these links. Reference: CSS AlmanacCool tricks  Homer CSS (2008)Romancortes.com Animated your HTML 1.a(3) JavaScript JavaScript is used to bring interactivity on the web pages. JavaScript is based on the ECMA Script standard.  Every browser has JavaScript engines, which interpret the JavaScript code. As described in the previous sections that the HTML is responsible for the structure and semantic aspect for the webpage. And with the help of CSS, the look and feel, advanced layouts and interactivity can be added using animation and pseudo classes. JavaScript brings lots of interactivity to your pages. It is good to say that it adds wings to your creation. But sometimes these wings catch the fire, so we also know how to troubleshoot and prevent such instances from happening.  For e.g. If you ask your user to input their age. To validate the age, we can write the JavaScript code and validate, whether the input is correct or not. To recap and understand the HTML, CSS and JavaScript in brief. We can refer to the above presentation. 2. ECMA Script and new versions ECMAScript describes the functionality of JavaScript. ECMAScript is maintained by ECMA International. The aim of ECMA Script is to ensure that webpages can run the same JavaScript code across different browser, & it is also interoperable with other programming language. In this context the Interoperability means that other programming language can invoke JavaScript function. Programming languages such as Dart can run JavaScript code. Some framework such as Blazor in the world of . NET can invoke functions written in JavaScript. In terms of specification it tries to draws the line of standard for different browser vendors. Microsoft, Firefox, Google, Chrome, Opera & Apple each has its own browsers which runs on different operating systems whether it is on Windows, Linux and macOS. Sometimes the browser vendor takes a lead while implementing a feature. But the specifications for that feature are written later by standard body (ECMA International). The new feature may be adopted by another browsers vendor later in the evolution process.  Different browser vendor has different development life cycle in terms of feature’s implementation. And it takes time for the specification to become a standard. And the new version of browser is released by multiple vendor with the specification and takes time to become a standard on Web. In past few years since ECMAScript has undergone various revisions and changes as described by ES6, ES7, ES8 & ES9 & more we will see in future. And these changes have resulted into the major impact on the JavaScript syntax. More references: ECMA Script version historyECMA Script2. Intro to React & Virtual DOM React is a library which is publicly released by Facebook in 2013. React was created by Jordan Walke, a software engineer working at Facebook. React allows us to divide our code into components. And these components communicate with each other in a unidirectional flow. As the components follows a standard development structure in nomenclature and design patterns. This helps in reducing of the knowledge gaps when different team members work and manage a project in which they have not worked from scratch.  React is based on the Functional programming principles as the design pattern. It is also follow the DRY principle. DRY stands for Don’t repeat yourself. That means any piece of code which serves a specific task or function should not be repeated as the duplicate code. But we can declare it as a component and increase the reusability. Design pattern is a wide topic. If you are interested to know more about the design pattern you may check out these references.Addyosmanirefactoring.guru2.b Quick timeline of React release Technology goes through a lot of wear and tear before it is adopted in mainstream and it also need to prove it's worth in real life production environment. The complete timeline of React release is available on GitHub. Some of the interesting highlights from React release. VersionRelease DateDescription0.3.029th May 2013Public release0.13.010th March 2015Support for ES6 Classes15.007th April 2016New changes on how React interacts with DOM, added support for SVG attributes, Dropped support for IE816.026th September 2017MIT license. Reduced file size. Better error handling16.505th September 2018Added support for React Devtools profiler (Flame chart, Ranked chart, Component chart & more)16.816th February 2019Introduced concept of hooksReference: Github.comRisingstack.com2.c Component driven development The beauty to work with React is that you can structure and assemble your code in components. The parent component can contain various child components. The parent component passes the data values to child, to maintain the uni-directional data flow. For data driven apps, React seems to be a good choice. 2.d  Virtual DOM - The secret sauce of DOM Optimisation Before we understand Virtual DOM, let’s take a look at DOM. DOM refers to document object model.DOM is referred by the browser to render the HTML. The HTML is converted into DOM. To simply visualise the DOM you can think of a tree trunk and which has its roots spread down below.In DOM visualisation tree we can see that there are different nodes which are connected to html. In DOM, whenever the new nodes are inserted and deleted there is cost in terms of computation and memory footprint during such operations. And this is a little costly affair. Virtual DOM acts as performance optimiser in these operations.  The Virtual DOM has two copies, one is the master copy of the node and another one is the copy of the changes to be done. Virtual DOM reduces the cost in terms of memory and processing time to apply the changes. It applies the minimal changes required on the DOM. The process is also called reconciliation and is achieved by render() function in React. Reference: View Live DOM Tree.d3.DOM VisualizerReconciliation3. Getting Started3.a Picking the development IDE or the Editor To work with code, we need an editor which can provides us the following: An engaging developer experience Notify and spot errors in advance Can perform autocomplete, syntax highlighting and maintain readability of code Easy to customise and provide plugins to help in developer workflow Also provide us flexibility to create our own plugins And help in code collaboration while working with multiple team members. There are various editors available for developers in market such as Sublime, Atom, Brackets and Visual Studio Code & WebStorm IDE.  All of them have their pros & cons.  In our current project we are sticking to Visual studio code. It is available for Windows, Mac and Linux.  You may download the editor based on your operating system.3.b Environment Setup To run React we will require Node.js on our operating system. Node.js is written by Ryan Dahl and is based on Chrome V8 engine.  Download Node.js & visit the url And we will install the release with even number and LTS (Long term support) We will be installing the Node.js version 12. It also includes npm which we will use to run our first app in React.  To run Node.js we can use command prompt on Windows and use Terminal on macOS.To check the Node.js version, we need to run the following command. node --versionAs you can see from screenshot that we have installed version 12 (v12.18.2) After installation of Node & npm.we will be creating to create a React app with command line interface (CLI). mkdir CodefactoryInstallation of create-react-app I have created a directory called Codefactory.  And in that directory, I am going to run the following command npx create-react-app my-appAfter couple of minutes, the packages will be installed. 4. Quick intro to Node & NPM. In the previous sections we have mentioned the use of Node and NPM. Node.js help developers to use JavaScript as the main language to build their apps. It is open source.  Some of its salient features are: Event driven Non-blocking I/O (input/output) cross platform run time environment Based on Chrome V8 JavaScript EngineRyan Dahl is the creator of Node.js. V8 supports new features of JavaScript and those features are made available to Node.js. And which keep the Node.js in mainstream based on the recent development and upgradation happening in the ecosystem of JavaScript and ECMAScript. Since modularity is much needed and required by developers. Node.js follows the concepts of modules as characterized by NPM. NPM is a package manager for Node.js modules and various packages are available for developers to test and experiment with their code. Official site.References: Node.js Ryal Dahl (2009) 5. Your first React app Start with the boilerplate app Now let's go back to terminal & run our app. We will go to directory my-app and after running the following command cd my-appNow you are in my-app directory, where the npx has downloaded the dependencies and modules.  5.2 File structure of React app Now, we will go to Visual studio code. We will go to menu bar and Add the folder my-app to workspace. In the Visual studio, the explorer will list down the files under the directory structure.  5.3 Run your React app Now is the time to run the React app.  To open terminal go to menu bar and go to Terminal > New Terminal. This will open the terminal at the bottom. We need to type following command in terminal to start the app.  npm start The command line will instruct the app to open in a new browser So, here we can see the app running. Good job so far!And as per the instructions from screenshot we will open the App.js The App.js will show a bunch of import statements and function App()There are various methods to create React app via CLI such as yarn and npm on local system. In case you are facing problems during installation. As an alternative approach to create a React app, you can check StackBlitzAnd create a new workspace of React It will provide you an online playground to tinker and play with the source code in the browser itself. At the left there is a workspace and at the right output from the app. It will show you the index.js which show the import statement, class App component declaration and the render() function. The render function contains JSX. And this allow us to write HTML in JS. This is for a little human friendly version for readability for both experienced programmers and newbie. Reference 5.4 Debugging tool React provides the React Developer tools to check and inspect the components created. It is a very handy tool for debugging. To install React developer tools we will open the below url in google chrome and install add-on from chrome web store  Once we have clicked on Add to Chrome, the tool will be installed.  To open the tool go to your project at localhost. And right click it will show the context menu and click on inspectTo open the tool go to Components tab as shown below:6. Tinker and Play Once we have opened the file App.js in our main project created from CLI. We can tinker around and play with the code. On line number 10, We have a paragraph tag. We can choose any message we want to write and see how it appears on the React app. For E.g. I have added this message in <p> Paragraph tag and inside of the paragraph tag there is a right foot icon enclosed in <big> Bigger text tag. Once we save the file, it will auto reload on the app. So, the auto reload feature saves us from manually load the browser when new changes are saved to disk.  <p >          A Journey of a Thousand Miles Begins with a Single Step.           <big></big> </p >Now feel free to introduce your messages, add some tags and play around. I hope this will serve a good starting point for you to learn and practice. Before you acquire the skills to become a React developer, I hope the understanding of HTML, CSS and JavaScript will give you a good foundation. Happy Learning!.Become a pro at Web Development with the help of our  React training courses. Experience Immersive Learning. 

Step-by-Step: Create a React Project From Scratch

7K
Step-by-Step: Create a React Project From Scratch

Hello learners. In this tutorial we will learn How to create a new React app. 

Before we begin, we need to understand few things. These tutorials are aimed for the aspiring and seasoned web developers & designer. 

If you are an aspiring web developer who wants to establish their career in React and other modern frontend technologies, these tutorials will provide you the basic understanding that you need to learn, rehearse and practice. And some additional links as a part of suggestive reading, which you can further dwell upon. 

As a lifelong learner, we need to be open to new ideas however they may challenge your beliefs at first.  

Technology is a work in progress. It composes of sections of stable parts which can be applied to solve the problem of our lives. And some sections which are the part of debate and undergoing experimentation and transformation by the pioneers who forged & nurture the systems. 

The cutting-edge technology tends to follow approximately the following adoption curve.

Technology Adoption Lifecycle

Source: Crossing the Chasm  (1990) -Author: Geoffrey Moore  

 
Technology Adoption Lifecycle 

As you can see, the curve is divided among 5 sections as categorized by the work of: 

  • Innovators 
  • Early adopters 
  • Early majority 
  • Late majority  
  • Laggards

Area under the curve represents number of customers  

During the second phase, there is an important phase known as Chasm. 

Any nascent technology which becomes main stream must grow this phase with the help of Early adopters along with innovators. And every promising technology has gone through this phase before it has gained enough momentum and has gone mainstream. 

Before we learn React. We need to learn some concepts. And It will be good to have some basic understanding of how internet works. There are various technical jargon associated and it is a broad topic. If you are complete starter, I hope it will give you some base. 

We will try to understand and answer the following: 

  1. What is Client & Server? 
  2. What is meant by HTTP?

Client & Server 

When a user is connected to the internet with the help of browser (Google Chrome, Mozilla Firefox, Internet Explorer, Safari & Opera). 

And when we type or do the google search with the help of keywords. We are presented a list of search results. The user computer is a client and google search engine act as server. As it serves to your queries in the form of the best matched results in a reasonable short time, it is good to say that the search results are produced at the blink of an eye. 

HTTP

World wide web (W3C) is a consortium which governs the internet. It has set of rules and protocols which defines how the different machines can communicate over the internet. Sir Tim burner Lee is the inventor of the W3C.

HTTP

HTTP is a protocol, which tells and describe the transmission of hypermedia on the internet. It is designed based on the client server concept. In which one system is a client which seeks the information and other system is a server who act and fulfil the request of the client. 

In HTTP, there are various status codes for server, and it describes the status of server based on the client request.  

Whether the request has been 

  • Successful 
  • any error conditions on Client & Server 
  • redirected by server & so on.

1.a(1) HTML 

HTML is a mark-up language which is used to create hypermedia document on the internet. Hypermedia based documents are used to exchange information on the internet. HTML should not be confused with programming language such as C, C++, Java & C#. 

Let’s write a Hello World! HTML document as below: 

<!DOCTYPE html>
<html lang="en"> 
<head> 
<meta charset="UTF-8"> 
<title>HTML 5 Document</title> 
</head> 
<body>Hello World!</ body> 
</html>

To run the above code we can write it down or copy & paste in our favorite text editor and save it as Hello World.html. Please note .html is the file extension. And once we open the file with the browser it will show us the output as below.

Create a React Project from Scratch

HTML is composed of various tags which defines the document and it's semantic. Semantic add meaning to the content as expressed by enclosing tags and it is not purely for visual presentation purpose.  

The HTML 5 document begins with <!DOCTYPE html> 

HTML has also undergone various revisions and modifications. 

For e.g. If We need to present the information as paragraph.  

Then we need to use < p > tag. 

For Tabular data < table >, Order list < ol > & unordered list < ul > and so on. 

References:

 1.a(2)CSS 

Brief history

CSS refers to the cascading style sheets. In the beginning year of the HTML, when HTML was used primarily to exchange information with the help of HTML document on the internet.  

There was limited functionality to style the webpages. In fact, there were some tags which allows to style a page and change its formatting. But there was no separation of concerns, for e.g. the formatting tag and its associated attributes were often mixed with semantic HTML.
Create a React Project from Scratch

And one of the early innovators Håkon Wium Lie recognized that there is a need of web page styling language which can address the presentation part of the webpages including the layout. And there is a need of separation of concerns.  

Håkon Wium Lie along with the co-inventor Bert Bos had written the specification of CSS. 

< table> & its sibling tags were heavily used to structure the layout of the webpages. 

For E.g. To create multi column layout < table> were frequently used. It worked well to create the initial push to the web layouts, but it has own draw backs.  

More on the history of CSS

To know more about how we can use CSS, we will start with previous code. To change the text color of Hello World! from black to green, we will declare a stylesheet called text.css. 

Naming convention for filename plays important rule, in recalling the file name when your source code becomes huge. It is good to start building on these habits. 

Hello World.html 

<!DOCTYPE html> 
<html lang="en"> 
<head> 
<meta charset="UTF-8"> 
<link rel="stylesheet" type="text/csshref="text.css" /> 
<title>HTML 5 Document</title> 
</head> 
<body>Hello World!</body> 
</html> 

 Text.css 

body{ 
font-family: 'Arial', Helvetica, Verdana; 
color: red; 
font-weight: bold; 
font-size: large; 
}

Create a React Project from Scratch

As you can see from the browser, it displays the Hello World! text in red color and font appearance is bold & larger. 

CSS has lots of modules which helps us to create sophisticated layouts, cool animations, image processing using css filters, accessibility (a11y) & much more. 

The current version of CSS is CSS3. As technology gradually evolved, so did the CSS.  

It is maintained by CSS working group, which consists of invited experts and working group members.  

If you are interested to explore more you may check some of these links. 

Reference: 

CSS Almanac

Cool tricks  

Homer CSS (2008)

Romancortes.com

Animated your HTML 

1.a(3) JavaScript 

  • JavaScript is used to bring interactivity on the web pages. 
  • JavaScript is based on the ECMA Script standard.  
  • Every browser has JavaScript engines, which interpret the JavaScript code. 

As described in the previous sections that the HTML is responsible for the structure and semantic aspect for the webpage. And with the help of CSS, the look and feel, advanced layouts and interactivity can be added using animation and pseudo classes. 

JavaScript brings lots of interactivity to your pages. It is good to say that it adds wings to your creation. But sometimes these wings catch the fire, so we also know how to troubleshoot and prevent such instances from happening.  

For e.g. If you ask your user to input their age. To validate the age, we can write the JavaScript code and validate, whether the input is correct or not. Create a React Project from Scratch

To recap and understand the HTML, CSS and JavaScript in brief. We can refer to the above presentation. 

2. ECMA Script and new versions 

ECMAScript describes the functionality of JavaScript. ECMAScript is maintained by ECMA International. 

The aim of ECMA Script is to ensure that webpages can run the same JavaScript code across different browser, & it is also interoperable with other programming language. In this context the Interoperability means that other programming language can invoke JavaScript function. 

Programming languages such as Dart can run JavaScript code. Some framework such as Blazor in the world of . NET can invoke functions written in JavaScript. In terms of specification itries to draws the line of standard for different browser vendors. Microsoft, Firefox, Google, Chrome, Opera & Apple each has its own browsers which runs on different operating systems whether it is on Windows, Linux and macOS. Sometimes the browser vendor takes a lead while implementing a feature. But the specifications for that feature are written later by standard body (ECMA International). The new feature may be adopted by another browsers vendor later in the evolution process.  

Different browser vendor has different development life cycle in terms of features implementation. And it takes time for the specification to become a standard. And the new version of browser is released by multiple vendor with the specification and takes time to become a standard on Web. In past few years since ECMAScript has undergone various revisions and changes as described by ES6, ES7, ES8 & ES9 & more we will see in future. 

And these changes have resulted into the major impact on the JavaScript syntax. More references: 

ECMA Script version history

ECMA Script

2. Intro to React & Virtual DOM 

React is a library which is publicly released by Facebook in 2013. 

React was created by Jordan Walke, a software engineer working at Facebook. React allows us to divide our code into components. And these components communicate with each other in a unidirectional flow. As the components follows a standard development structure in nomenclature and design patterns. This helps in reducing of the knowledge gaps when different team members work and manage a project in which they have not worked from scratch.  

React is based on the Functional programming principles as the design pattern. It is also follow the DRY principle. DRY stands for Dont repeat yourself. That means any piece of code which serves a specific task or function should not be repeated as the duplicate code. But we can declare it as a component and increase the reusability. Design pattern is a wide topic. If you are interested to know more about the design pattern you may check out these references.

Addyosmani
refactoring.guru

2.b Quick timeline of React release 

Technology goes through a lot of wear and tear before it is adopted in mainstream and it also need to prove it's worth in real life production environment. 

The complete timeline of React release is available on GitHub. 

Some of the interesting highlights from React release. 

VersionRelease DateDescription
0.3.029th May 2013Public release
0.13.010th March 2015Support for ES6 Classes
15.007th April 2016New changes on how React interacts with DOM, added support for SVG attributes, Dropped support for IE8
16.026th September 2017MIT license. Reduced file size. Better error handling
16.505th September 2018Added support for React Devtools profiler (Flame chart, Ranked chart, Component chart & more)
16.816th February 2019Introduced concept of hooks

Reference: 

Github.com

Risingstack.com

2.c Component driven development 

The beauty to work with React is that you can structure and assemble your code in components. The parent component can contain various child components. The parent component passes the data values to child, to maintain the uni-directional data flow. 

For data driven apps, React seems to be a good choice. 

2.d  Virtual DOM - The secret sauce of DOM Optimisation 

Before we understand Virtual DOM, lettake a look at DOM. DOM refers to document object model.DOM is referred by the browser to render the HTML. Create a React Project from Scratch

The HTML is converted into DOM. To simply visualise the DOM you can think of a tree trunk and which has its roots spread down below.

Create a React Project from Scratch

In DOM visualisation tree we can see that there are different nodes which are connected to html. In DOM, whenever the new nodes are inserted and deleted there is cost in terms of computation and memory footprint during such operations. And this is a little costly affair. 

Virtual DOM acts as performance optimiser in these operations.  

The Virtual DOM has two copies, one is the master copy of the node and another one is the copy of the changes to be done. 

Virtual DOM reduces the cost in terms of memory and processing time to apply the changes. It applies the minimal changes required on the DOM. The process is also called reconciliation and is achieved by render() function in React. 

Reference: 

View Live DOM Tree.

d3.DOM Visualizer

Reconciliation

3. Getting Started

3.a Picking the development IDE or the Editor 

To work with code, we need an editor which can provides us the following: 

  • An engaging developer experience 
  • Notify and spot errors in advance 
  • Can perform autocomplete, syntax highlighting and maintain readability of code 
  • Easy to customise and provide plugins to help in developer workflow 
  • Also provide us flexibility to create our own plugins 
  • And help in code collaboration while working with multiple team members. 

There are various editors available for developers in market such as Sublime, Atom, Brackets and Visual Studio Code & WebStorm IDE.  All of them have their pros & cons.  

In our current project we are sticking to Visual studio code. It is available for Windows, Mac and Linux.  

You may download the editor based on your operating system.

3.b Environment Setup 

To run React we will require Node.js on our operating system. Node.js is written by Ryan Dahl and is based on Chrome V8 engine.  

Download Node.js & visit the url

And we will install the release with even number and LTS (Long term support) 

We will be installing the Node.js version 12. It also includes npm which we will use to run our first app in React 

To run Node.js we can use command prompt on Windows and use Terminal on macOS.To check the Node.js version, we need to run the following command. 

Create a React Project from Scratch

node --version

As you can see from screenshot that we have installed version 12 (v12.18.2) 

After installation of Node & npm.we will be creating to create a React app with command line interface (CLI). 

mkdir Codefactory

Installation of create-react-app 

I have created a directory called Codefactory 

And in that directory, I am going to run the following command 

npx create-react-app my-app

After couple of minutes, the packages will be installed. 

4. Quick intro to Node & NPM. 

In the previous sections we have mentioned the use of Node and NPM. 

Node.js help developers to use JavaScript as the main language to build their apps. It is open source.  

Some of its salient features are: 

  • Event driven 
  • Non-blocking I/O (input/output) 
  • cross platform run time environment 
  • Based on Chrome V8 JavaScript Engine

Ryan Dahl is the creator of Node.js. 

V8 supports new features of JavaScript and those features are made available to Node.js. And which keep the Node.js in mainstream based on the recent development and upgradation happening in the ecosystem of JavaScript and ECMAScript. 

Since modularity is much needed and required by developers. 

Node.js follows the concepts of modules as characterized by NPM. 

NPM is a package manager for Node.js modules and various packages are available for developers to test and experiment with their code. 

Official site.

References: 

Node.js Ryal Dahl (2009) 

5. Your first React app 

Start with the boilerplate app 

Now let's go back to terminal & run our app. 

We will go to directory my-app and after running the following command 

cd my-app

Now you are in my-app directory, where the npx has downloaded the dependencies and modules.  

5.2 File structure of React app 

Now, we will go to Visual studio code. We will go to menu bar and Add the folder my-app to workspace. 

Step-by-Step: Create a React Project From Scratch

In the Visual studio, the explorer will list down the files under the directory structure 

5.3 Run your React app 

Now is the time to run the React app.  

To open terminal go to menu bar and go to Terminal > New Terminal. This will open the terminal at the bottom. 

We need to type following command in terminal to start the app.  

npm start 

The command line will instruct the app to open in a new browser Create a React Project from Scratch

So, here we can see the app running. 

Good job so far!

And as per the instructions from screenshot we will open the App.js 

The App.js will show a bunch of import statements and 

function App()

There are various methods to create React app via CLI such as yarn and npm on local system. 

In case you are facing problems during installation. 

As an alternative approach to create a React app, you can check StackBlitz

And create a new workspace of React 

It will provide you an online playground to tinker and play with the source code in the browser itself. Create a React Project from Scratch

At the left there is a workspace and at the right output from the app. 

It will show you the index.js which show the import statement, class App component declaration and the render() function. The render function contains JSX. And this allow us to write HTML in JS. This is for a little human friendly version for readability for both experienced programmers and newbie. 

Reference 

5.4 Debugging tool 

React provides the React Developer tools to check and inspect the components created. It is a very handy tool for debugging. 

To install React developer tools we will open the below url in google chrome and install add-on from chrome web store  

Create a React Project from ScratchOnce we have clicked on Add to Chrome, the tool will be installed.  

Step-by-Step: Create a React Project From Scratch

To open the tool go to your project at localhost. And right click it will show the context menu and click on inspect

To open the tool go to Components tab as shown below:

Step-by-Step: Create a React Project From Scratch

6. Tinker and Play 

Once we have opened the file App.js in our main project created from CLI. We can tinker around and play with the code. 

On line number 10, We have a paragraph tag. We can choose any message we want to write and see how it appears on the React app. 

For E.g. I have added this message in <p> Paragraph tag and inside of the paragraph tag there is a right foot icon enclosed in <big> Bigger text tag. Once we save the file, it will auto reload on the app. So, the auto reload feature saves us from manually load the browser when new changes are saved to disk. 

 <p > 
        A Journey of a Thousand Miles Begins with a Single Step.  
        <big></big>
</p >

Create a React Project From Scratch

Now feel free to introduce your messages, add some tags and play around. I hope this will serve a good starting point for you to learn and practice. 

Before you acquire the skills to become a React developer, I hope the understanding of HTML, CSS and JavaScript will give you a good foundation. HappLearning!.

Become a pro at Web Development with the help of our  React training courses. Experience Immersive Learning. 

Gaurav

Gaurav Mishra

Author

Gaurav Mishra is an expert in user-interface development and user-experience design, with more than 13+ years of experience. Comfortable to work with any kind of technology, he has growth mindset and keep a beginner mind. He has provided workshops and training in UI development, UX design, and Drupal. He has mentored and trained various students around the world. Gaurav has played the key role in the success of many organizations and likes to build products and services from scratch which delight people.  He likes to challenge the status quo to bring out the best from team & reshape the organisation culture. He likes all genres of music, from Indian classical to club music. 

Join the Discussion

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

Suggested Blogs

Learn Nodemailer Module in Node.js

In this tutorial, we will learn how to send email in Node.js using the nodemailer npm package.For the email provider, we are going to use Sendinblue. Prerequisites Node.js (>v6.0.0 for nodemailer module) Code Editor (For Ex. VS Code, Atom) An account in SendinblueStart by creating a free account in Sendinblue. A Sendinblue free account offers 300 mails/day. Its setup is easy and straightforward. An introduction to Nodemailer Nodemailer, an open source project started in 2010, is annpm module for Node.js applications to send emails. Today, nodemailer is a de facto to send an email in Node.js. Highlights of Nodemailer It is a single module with zero dependencies  It supports HTML Content  Allows you to easily add attachments to messages Supports SMTP as default transport method; other supported transport methods are SES, Sendmail, Stream. OAuth2 authenticationGetting Started For this tutorial, I am using Nodejs v12.16.1 and VS Code as the Code Editor. Create a new directory nodemailer-example.  Open the terminal or cmd inside the directory and run  $ npminit --yes It will initialize a new npm package. Install dependencies Following different npm packages, we are going to use in this project. nodemailer – To send the mail express – To create APIs cors – To resolve the cross originresource sharing body-parser – To extract the body from the API request dotenv – To access the environment variables $ npm install --save nodemailer express cors body-parser dotenv This command will install all the dependencies. Now, we can start the coding. Project Structure Open the nodemailer-example in the code editor and create the following folders and files in it; not to worry, I will be explaining all the files and commands involved.  nodemailer-example    |- routes      |- mail-api.js    |- src      |- send-mail.js    |- template      |- mail.html    |- .env    |- index.js Sendinmail Setup Login to your Sendinmail account. From the top-left menu, select SMTP & API. Select the SMTP tab. Click on Create a new SMTP key. Copy the key at some safe place.  You can deactivate the SMTP key anytime. Now, open the .env file and create 2 key-value pair. USER=YOUREMAILADDRESS  PASS=xxxxxxx-xxxxxxxxxxxx-xxxxxxxxxxxxxxxxxxxxxx USER: The email address using which you created the sendinmail account. PASS:SMTP Key By using .env file we are not exposing the credentials to the web.  Using environment variables in the project is an industrial standard.  Source Code Open the send-mail.js in the editor. Copy and paste the below code in it."use strict";  require("dotenv").config();  constnodemailer = require("nodemailer");  /**   * sendEmail   * @param{Object}mailObj - Email information   * @param{String}from- Email address of the sender   * @param{Array}to- Array of recipients email address   * @param{String}subject - Subject of the email   * @param{String}text - Email body   */  constsendEmail = async (mailObj) => {  const{ from, to, subject, text } = mailObj;  try {  // Create a transporter  lettransporter = nodemailer.createTransport({  host:"smtp-relay.sendinblue.com",  port:587,  auth: {  user:process.env.USER,  pass:process.env.PASS,        },      });  // send mail with defined transport object  letinfo = awaittransporter.sendMail({  from:from, // sender address  to:to, // list of receivers  subject:subject, // subject line  text:text, // plain text body      });  console.log(`Message sent: ${info.messageId}`);  return`Message sent: ${info.messageId}`;    } catch (error) {  console.error(error);  thrownewError(  `Something went wrong in the sendmail method. Error: ${error.message}`      );    }  };  module.exports = sendEmail; Code Walk Through In the beginning, we are importing dotenv to get the environment variables from the .env file and nodemailer to send the email. The sendEmailfunction accepts an object. This object has from, to, subject, text fields. Please note that, from and USER must be same. The nodemailer.createTransportreturns a mail object. The transporter variable is storing the mail object.  let transporter = nodemailer.createTransport({       host: "smtp-relay.sendinblue.com",       port: 587,       auth: {         user: process.env.USER,         pass: process.env.PASS,       },     });Open SMTP tab in your sendinmail account and cross check the host and port.In the auth object, we are passing the user and password from the environment variable.Send the mail using sendMail method.// send mail with defined transport object     let info = await transporter.sendMail({       from: from, // sender address       to: to, // list of receivers       subject: subject, // Subject line       text: text, // plain text body     });It returns a Promise of Send Message Info. In the end, it is returning the message id.  Express Route The sendEmail method is ready.  Let’s create an express route for it. This is the API endpoint using which we can access the sendEmail function. Open the mail-api.js in the code editor and paste the below code. constexpress = require("express");  constrouter = express.Router();  constsendMailMethod = require("../src/send-mail");  // Post request to send an email  router.post("/sendmail", async (req, res) => {  try {  constresult = awaitsendMailMethod(req.body);  // send the response  res.json({  status:true,  payload:result          });      } catch (error) {  console.error(error.message);  res.json({  status:false,  payload:"Something went wrong in Sendmail Route."          })      }  }) module.exports = router; The express framework provides a Router method to create different HTTP methods. Here, we have created a POST method to send the mail.  Instead of extracting the req.body parameters, we passed it as it is. The benefit of this approach is that if there is a change in argument or position, then we would not have to change it in all the places.  In the end, we are exporting the router. Now, this can be used in the server side. Express Server Now, it’s time to create a server and expose the routes on it. Open the index.js and paste the below code in it. "use strict";  constexpress = require("express");  constbodyParser = require("body-parser");  constcors = require("cors");  constapp = express();  constmailAPI = require("./routes/mail-api.js");  // Express body parser  app.use(cors());  app.use(bodyParser.json());  app.use(  bodyParser.urlencoded({  limit:"50mb",  extended:false,  parameterLimit:50000    })  );  // use the routes specified in route folder  app.use("/api/v1", mailAPI);  constport = process.env.PORT || 4444;  //listen to the server  app.listen(port, function () {  console.log(`listening to the port ${port} .....`);  }); The route is available on /api/v1/sendmail. Run the server. $ node index.js  listening to the port 4444 ..... Send an Email using API There are couple of methods to test the API. Using the Postmanor using the Curl command. Using Postman Install Postman on your machine if it is not installed. Create a POST request. URL: http://localhost:4444/api/v1/sendmail Content Type: JSON – Body tab > select JSON from dropdown Request Body:  {  "from": "hello@schadokar.dev",  "to": ["shubham@schadokar.dev"],  "subject": "Mail from Nodemailer",  "text": "Sending an email using nodemailer package."  } Hit Send. Make sure the server is running. On Success, the response returns the message id. Now, check your mailbox. If you are unable to find the mail in your Inbox, check the promotional mail folder. Using Curl CommandOpen the terminal or cmd.In the below curl command, change the parameters and enter.curl -X POST http://localhost:4444/api/v1/sendmail -H "Content-Type:application/json" -d '{"from": "hello@schadokar.dev","to": ["shubham@schadokar.dev"],"subject": "Mail from Nodemailer", "text": "Sending an email using nodemailer package."}'In this example, we have sent a simple text message to the recipient.  Nodemailer also gives you an option to send the message in HTML format. Mail template Open the mail.html in the code editor and paste the below code. 
6797
Learn Nodemailer Module in Node.js

In this tutorial, we will learn how to send email ... Read More

Full Stack Development – the Hottest Developer Skill for the Digital Age

With over 1.7 billion websites worldwide and 4.54 billion people using the internet actively, the need for heightened customer experience is on the rise. This is one of the major reasons why professionals who are adept at handling both the client-side and server-side interfaces of an application/website have become more important than ever. It has been estimated that by the next decade, there will be 300,000 new developer jobs in US. The Full Stack developer role is the No.1 position to be filled in 2020 according to 38% of hiring managers. This is closely followed by the role of a back-end developer.Handsome pay packagesThe average annual salary for a full-stack developer is about $110,737 per annum. Even beginners are offered about $58,000 per year and on the other hand, experienced professionals would earn up to $188,253 per year.These professionals are paid handsomely because enterprises are aware that a full stack developer does the job of two professionals (back-end and front-end developer).Plenty of growth opportunitiesAs per reports by The United States Bureau of Labor Statistics, full-stack development job opportunities will increase from 135,000 to 853,000 by the year 2024. This is quite promising for aspiring full stack developers as an ocean of opportunities will be available for them in both startups as well as in multi-national organizations.Skills to become a Full Stack developerBecoming a full-fledged full stack developer is not child’s play. It takes a wide range of skills to become a good full stack developer. Below are the mandatory skills:Front-end skills: They should be well-versed with basic front-end technologies like HTML5, CSS3, and JavaScript. They should also be comfortable working with front-end frameworks or third-party libraries such as JQuery, SASS, and AngularJS.Programming languages: They should be aces in at least one server-side coding language like Java, Python, Ruby or .Net.Databases: They should be efficient at handling data from databases like MySQL, MongoDB, Redis, Oracle and SQLServer.Version control systems (VCS): Full stack developers must be aware of Git so that they can make appropriate changes to the codebase.Basic design skills: Awareness about the basic prototype design and UI/UX design is essential to become a successful full stack developer.Server and API: They should have adequate exposure to Apache or Linux servers as well as web services.The way forward for Full Stack developersThe growing demand for full-stack developers is due to the ample benefits they offer to organizations. With technology evolving at a rapid pace, foresighted companies will keep adding them to their workforces. Full stack development became the No.1 developer skill because these developers are trained to multi-task various technologies and products. For aspiring full stack developers out there, now is the best time to make the most of these opportunities.Real products require real challenges. Check out our live online workshops and build your portfolio of projects.
4858
Full Stack Development – the Hottest Develop...

With over 1.7 billion websites worldwide and 4.54 ... Read More

What are React Component Lifecycle Methods

React is the most popular JavaScript library used to create interactive UI for web applications. It is a component-based library where different parts of a webpage can be encapsulated by components which are quite easy to create, manage and update. React allows us to create Single Page Applications which maintain the state of individual components on an app without having to reload it.  What are React Components? Developers who are new to JavaScript libraries and frameworks like React and Angular might ask the question, “What is a component?” Well, in very simple words, a component is a unit of code which includes JavaScript and HTML to build a part of a web page. It acts like a custom HTML element. It is reusable and can be as complex as you want it to be. For example, imagine that you are creating a very basic application with header, footer, and body. The header can be a component; the footer can be another component and the body can be yet another one or even might consist of multiple components.One of the most useful characteristics of React is its ability to integrate reusable components in a project. Reusability is the characteristic of a component which allows it to be used again, thereby reducing the amount of code a developer has to write. In our example here, the header can be a reusable component and can be used on all the pages of the application, which makes it easy to maintain and update. What does a component look like? Here is a simple example of a react component which contains a simple form. This is a class-based component. React also supports function-based components. As you can see in the code below, App is a user-defined class which inherit from React’s Component class and it has a render method which returns HTML code. As the name suggests, the render method returns and renders HTML to our browser. Every component has to return HTML which is rendered to the user’s browser by render method.import React, { Component } from 'react';  class App extends Component {    handleChange(event) {      this.setState({value: event.target.value});    }    render() {      return (                              Username:                                            Password:                                              );    }  }    export default App; In the above example, we have created a login form where there are 2 input boxes for the user to enter their username and password and then submit the form. We have assigned an event handler to form which will handle the login event in component.We have exported our component (using export default App) so that it can be rendered inside other components.This is a very basic example of component, but this can be as complex as you want it to be. But it is always advised to make your component independent and it should represent only a part of your page which can be reusable as well. It can return complex HTML included with JavaScript to handle complex features in your application.Component as a class React allows us to create component in the form of class as well as functions. While creating component as class you need to define a class which extends React.Component class. Component class has many features which the deriving class can use to maintain the state throughout the lifecycle. In case you want to have more custom features, you can create your own base component class which derives from Component class, and then your component classes can derive from your base component class. What do we mean by Component Lifecycle?Lifecycle of a component is the set of different stages (also known as lifecycle hooks) a component goes through while it is active. Stages could be when a component is created or when any changes are made to the component and many others. There are different methods executed by React at different points of time between when a component is created and at the end when it is destroyed and not in use. One such hook or method we have already seen in the code above, which is render(), and it is executed by React to render the component. We can override these methods and perform certain tasks in those methods, but every lifecycle serves a different purpose and it can be a nightmare if we ask them to do something that they aren’t supposed to or are not very good at. As a developer we should be aware of what those different stages are, what happens in those stages, in what order they execute and how we can make the best use of it. Understanding the lifecycle of components also helps us predict behavior of a component at different stages, which makes it easier to work with them. Managing a large set of components in an application can get you in trouble if you do not know how they work behind the scenes.Props and State Before we start with lifecycle hooks, lets understand what props and state are as they are most commonly used properties in component classes. Props It is a keyword which means properties. Props are used by callers of components to pass properties to the called component in a uni-directional flow. For example, if Parent component renders child component, it can define props and pass them to the child component which is then available and accessible by this.props. Another thing to note here is that props is a ready-only attribute which means data which is passed by parent should not be changed by client components. State State is a plan JavaScript object which defines the current state of any component. It is user defined and can be changed by lifecycle hooks. Ideally state should contain only data which is going to be rendered on DOM. State has getter and setter methods this.getState() and this.setState() which as the names suggest are used to access and update State. It is good practice to use setState method to update State and treat State as an immutable JavaScript object.Since there are many lifecycle hooks a component goes through, it would easier to understand if we start with the hooks which are executed when a component is created.Lifecycle hooks while Mounting [These lifecycle hooks are executed in order as listed, when a component is created]constructor(props) This is not a component lifecycle hook, but it is important to mention here and to be aware that Constructor is executed before it is mounted. Constructor receives props(properties of a component) as an argument which then can be passed to base class using super keyword if we define the constructor.  It is not mandatory to define constructor in component class, but if you do to perform any logic, then you need to call base constructor using super keyword.  Mainly constructors are used: To Setup local state of component with this.state To bind event handler methods. This is what a simple constructor would look like.import React, { Component } from 'react';  class App extends Component {    constructor(props) {      super(props);      this.state = { value: 0 };      this.handleClick = this.handleClick.bind(this);    }  } this.state should be called only inside constructor, to update the state in other methods use this.setState() method.  If constructor is required to do any heavy tasks, it will impact the performance of component, and you should be aware of this fact.  getDerivedStateFromProps(props, state) After constructor, this lifecycle hook is called before render method is executed. It is called while mounting as well as whenever props have changed. This is not very commonly used, only in cases where props can change, and you need to update state of the component. This is the only use case where you should implement this lifecycle hook.This method is executed on every render and cannot access component instance.import React, { Component } from 'react';  class App extends Component {    getDerivedStateFromProps(props, state) {      if (props.value !== state.prevValue) {        return {          prevValue: props.value        };      }      return null;    }    }render() This is the method which is required to be implemented in component class. It can access props and state. This is where you can write your html and jsx code. You can also render child components in this method which will then be rendered as well. Before completing the lifecycle of parent, lifecycle of all child components will be finished. All this html and jsx is then converted to pure html and outputs in DOM. JSX is a JavaScript extension which creates React elements. It looks more like template language but it is empowered by JavaScript which allows it to do a lot more. It can embed expressions . JSX has different set of attributes than what we have in html. For example, while creating html using JSX you need to use attribute “className” instead of class. This is what a typical render method looks like:import React, { Component } from 'react';   class App extends Component {   render() {         return (        Click to go Home { this.state.home }       Go to Home         );   } } Alternatively you can also use React.createElement() method to create html using JSX.const element = React.createElement(       'h1',       {className: 'hello'},       'Hello, world!'     );componentDidMount() As the name suggests, componentDidMount() is invoked after the component is mounted, which means html has been added to DOM tree. It is a very commonly used lifecycle hook, as it allows you to do a lot of things including causing side-effects, setting up any subscriptions, or loading data from external endpoints. If you setup any subscription using this method, make sure to unsubscribe them in componentWillUnmount() lifecycle hook. You shouldn’t update state in this method using this.State() as it may cause performance issues. For assigning initial state you should use constructor(). import React, { Component } from 'react';  class App extends Component {    componentDidMount(){    // Component is rendered and now external calls can be made.      this.getDataAfterTimeOut();    }    getDataAfterTimeOut(){      setTimeout(() => {        this.setState({          data: 'Data is fetched'        })      }, 1000)    }  } Lifecycle hooks while Updating [Next set of lifecycle hooks are executed while a component is updating which can be caused by changes to props(properties) or state of component. These are invoked in order as listed below.] getDerivedStateFromProps(props, state) We have already talked about this. This is invoked every time a component is changed or updated. Any changes in properties or state which causes the component to be changed will invoke this method. shouldComponentUpdate(nextProps, nextState) shouldComponentUpdate() is invoked before rendering (not on initial rendering) but only when props or state has been changed. Even though it is not recommended you can use this lifecycle hook to control the re-rendering. This can lead to performance issues as well as bugs, so be careful while doing that.  In this method nextProps can be compared with this.props and nextState can be compared with this.state. This method can return true or false depending on whether you want to continue rendering by skipping the next lifecycle hooks. In either case it can’t prevent re-rendering of child components. Note that this method defaults to true which will not skip rendering and next lifecycle hooks and continue with execution. import React, { Component } from 'react';  class App extends Component {    shouldComponentUpdate(nextProps, nextState) {  // This value will determine if lifecycle execution is to be skipped or continued.      return nextProps.value != this.props.value;    }  } render() After shouldComponentUpdate lifecycle hook render is called, which we have already talked about, it prepares html and jsx code which then outputs to DOM. getSnapshotBeforeUpdate() getSnapshotBeforeUpdate() is invoked right before the recent changes are added to DOM. This lifecycle hook gives us an opportunity to capture any details we need from the DOM before it is updated with new content. For example, if you want to know the scrolling position of the user, which should be restored after the DOM has changed. Use cases for this lifecycle, while rare, can be of great value at times. The snapshot value which is captured and returned by this hook is passed as a parameter to another lifecycle hook componentDidUpdate() which we will talk about next. import React, { Component } from 'react';  class App extends Component {    getSnapshotBeforeUpdate (prevProps, prevState) {  // implementing this method here allows us to capture the snapshot of current dom tree.      if (this.state.value != prevState.value) {        return table.scrollHeight - table.scrollTop      }      return null    }  }componentDIdUpdate(prevProps, prevState, snapshot) componentDidUpdate is invoked when DOM is updated. It is only called on update, not on initial rendering. You can use this method to make data requests after checking if props have changed. You can also call setSatate() in this method, but make sure to wrap that in a condition else it will cause an infinite loop forcing re-rendering and affecting performance issues. Also it should be noted that value for snapshot will only be available if you have implemented getSnapshotBeforeUpdate() in your component; else value for snapshot will be undefined. Here is an example of componentDidUpdate. This is a very basic example where we have captured snapshot by implementing get Snapshot Before Update lifecycle hook. After that componentDidUpdate is invoked and content is overwritten with new dataimport React, { Component } from 'react';  class App extends Component {    getSnapshotBeforeUpdate(prevProps, prevState) {  // implementing this method here allows us to capture the snapshot of current dom tree.      document.getElementById("divContent").innerHTML =      "Before the update content is " + prevState.content;    }    componentDidUpdate(prevProps, prevState, snapshot) {  // You can access snapshot here to get data from dom before it was updated.      document.getElementById("divContent").innerHTML =      "New content updated " + this.state.content;    }  } import React, { Component } from 'react';  class App extends Component {    getSnapshotBeforeUpdate(prevProps, prevState) {  // implementing this method here allows us to capture the snapshot of current dom tree.      document.getElementById("divContent").innerHTML =      "Before the update content is " + prevState.content;    }    componentDidUpdate(prevProps, prevState, snapshot) {  // You can access snapshot here to get data from dom before it was updated.      document.getElementById("divContent").innerHTML =      "New content updated " + this.state.content;    }  } UnMounting [This is where lifecycle of a component ends when component is destroyed and removed from DOM. While Unmounting React gives us an opportunity to do something before component is destroyed, it can include clearing objects which have occupied memory to avoid memory leaks.] componentWillUnMount() componentWIllUnMount() is executed right after component is unmounted which means it is removed from DOM and destroyed. But before it is removed and destroyed, React gives us an opportunity to perform any cleanup we want to. For example, you might have setup subscriptions initially in componentDidMount() which you should unsubscribe when component is destroyed to avoid memory leaks in your application. You can also remove event listeners which were subscribed before. In this lifecycle hooks you should not update state of your component because component is not going to re-render now.import React, { Component } from 'react';  class App extends Component {    componentWillUnmount() {  // Component will be removed from DOM now.        // Unscubscribe subscriptions and events here.  document.removeEventListener("click", this.handleSubmit);    }  }Conclusion In this article we talked about React, its components and its different lifecycles. It is very crucial to understand the different opportunities that React provides through these lifecycle methods. There are many rules we need to follow while working with these hooks. Making them do something they can’t handle can cause performance issues or even infinite loops at times.  These lifecycle hooks work with props and state which are the most used properties of component class. Changes in state and props trigger different lifecycle hooks and even re-render the dom which is something you should be aware of. These lifecycle hooks are provided to intercept the different stages a component goes through and make the best use of it, but without understanding how they work it can break your application by causing performance issues or memory leaks. Hope this has been helpful. 
9273
What are React Component Lifecycle Methods

React is the most popular JavaScript library us... Read More