Search

What are the Pros and Cons of React

If you are a web developer, you are a JavaScript developer--by choice or by force. I mention by force because not many web developers like to work with vanilla JavaScript, especially ones who have worked with frameworks and languages where Object Oriented concepts are made easier for developers to work with. But this does not stop JavaScript from becoming the most widely used language in the world. The popularity of JavaScript has been growing rapidly over the past years.  For any web development, a lot of the work gets done by JavaScript at the user’s browser and at times it becomes difficult to manage vanilla JavaScript in large applications as it lacks the structure which developers enjoy in languages like Java, C# at the back end. Technology leaders identified this problem, and they came up with multiple solutions to make JavaScript not just easier to work with but also to give it performance boost and empowering browsers to do lot more without having to worry about managing complex state of applications as they grow to meet customer demand. React is one such solution along with Angular and Vue. What is React JS? ReactJS is a component-based JavaScript library created by Facebook. React makes it easier to create interactive UI using components and efficiently manage states of those components. Multiple components can be composed together to make complex applications without losing their state in DOM.  Even though we are talking about React as a tool for web application here, it can also be used for mobile application development with React Native, a powerful and open-source native library for mobile application. This is how a simple React component looks like. class HelloWorld extends React.Component {    render() {      return (        <div>          Hello world!        </div>      );    }  } What can we build using React JS? Being one of the most popular JavaScript libraries, React can be used to create anything you see on the web. It can be used for multiple requirements; be it a simple but interactive app like Instagram, or a complex streaming app with large userbase and support for multiple languages and regions like Netflix or an application like Facebook, with very large dataset and high complexity with the power to process more than a billion users’ requests parallelly. However, it is not just limited to highly scalable web applications, and you can also create mobile applications using React Native which is an open-source mobile application framework. You can create Android, iOS and Windows apps using this framework. In fact, the above-mentioned web applications “Instagram, Facebook, Netflix” mobile apps are also created using React Native. It gives developers a rich library to utilize the native features of a device to deliver high performance and highly interactive applications to users across the world. Pros 1. Component based architectureIt is not uncommon for vanilla JavaScript based apps to get into a stage, when managing state of data at user’s browser becomes a headache for developers. As the data and complexity of an application grow, it becomes difficult to maintain using vanilla JavaScript. The introduction of React components brings a highly sophisticated unit of a web page which can be independently created, maintained, and even reused. You can divide your web page into multiple components, and they can work independently. You can update one of them without having to worry about changes in others. This makes it very loosely coupled and at the same time available for working together by merging with other components to bring out the best of the web application’s abilities. This is not something unique in React library. In fact, components are the basic building blocks in the Angular framework as well, and a similar concept has been there in many MVC frameworks since a long time. 2. High PerformanceWith component-based architecture, React allows to create highly scaled Single Page Application or SPA, in which content is dynamically loaded during user interaction without loading the entire page. However, this can turn into a trap. Imagine having to update DOM for every change caused by user’s interaction on web page. Every action might force DOM (which is a tree structure) to refresh itself. And if your web page is complex, having multiple UI components this can cause massive performance blockage. To solve this, React uses the concept of Virtual DOM, which you can think of as a copy of your real DOM. Now all the changes caused by user’s interaction or other events are handled by the virtual DOM first, and only if it (the intelligence of React) thinks it is important enough to refresh the real DOM, the real DOM is refreshed. This saves us from massively repeating recreation of the DOM tree for every trivial change resulting in high performance application.3. ReduxBack to our SPA (Single Page Application), where there are multiple components sitting on one page and updated dynamically without reloading the entire page. Now all this sounds very simple and smooth. Which it is, until your components start talking to each other. Let’s say you have a web page where there are few form components which contains large forms with lot of controls, few table components, and a sidebar and header, footer. Content in tables must be updated when user submits form or part of forms. Also, you might want to update header when a new record is created. Now here, our table components have dependency on form components. These dependencies, along with communication between them can grow as your application grows. All this can make our data unstable as there is no way to know which data is latest or which is correct. There is no single source of data. This can cause poor user experience and also performance issues. To make sure that all your components are in sync with latest data, we need to have a--let’s just call it-- a ‘manager’ who manages our data, and provides a single trustworthy source which makes sure the data which the components have is correct and truthful. This manager and its team are known as Redux in React.  Redux forces components to avoid talking to each other directly or being dependent on each other, instead components send their data to redux and it is the responsibility of redux to update the components (which need those data) with new data. This way components are always updated with the latest data available without having to depend on each other.4. Easy to LearnThis is another pro of working with React as any developer with understanding of html and JavaScript can start learning React. Unlike other JS frameworks like Angular which introduce a lot of new terminologies, React uses most of what is already available. This makes it very easy to start with--another reason why it has grown to be the most popular JS library.  It provides more flexibility (which it derives from Vanilla JavaScript) and does not force developers to follow any specific pattern like MVC or any other architectural pattern. Development teams are free to choose their own style or patterns while working with an application. This allows vanilla JavaScript developers to work with component-based architecture without having to lose the freedom they enjoyed with vanilla JavaScript. 5. Mobile App DevelopmentIn a world where every platform, and every stack of an application requires you to learn a whole new tool or language or frameworks; React brings us the flexibility of using the same library over web and mobile applications. React Native allows us to create mobile applications on any mobile platform with the same React concepts and syntaxes. React Native helps you create interactive and high-performance mobile apps for any mobile device without having to learn a new tool or language. So far, we talked about what makes React so popular among development teams, but every technology has pros and cons. Let’s talk about why many teams are not willing to work with React and what makes it less reliable when you need a well-structured and stable JS library to work with. Cons  1. High Pace of DevelopmentThis is arguably the most discussed con of using React. React is not just a rapidly growing library, it is also rapidly changing, which forces its developers to update the way they write code. Now this is obviously annoying for most of the developers who are not comfortable with adopting new ways every Monday they start or the ones who are working on an application where changes are critical to customers. There are many industries which are critical to change where customers look for more stable tools and technologies. But this again depends on how expert team members are and if they can convince their customers to trust them with React.  2. Flexibility and Lack of ConventionsYes, you read it right. I know that we discussed it as an advantage of using React, but at the same time it is also a disadvantage in a broader sense. Libraries, languages, or frameworks have their global standards of how developers work with them, and what styles or patterns they follow. This is useful because when developers change teams, they have an idea of what patterns or styles the new team might be following; whereas among React development teams it is not easy to predict what styles or standards a team might follow, making it harder for new developers to work with new teams and their standards. Developers who have worked with frameworks which follow a fixed structure and set of conventions might not find React very attractive to work with. 3. Not a full-featured frameworkEven though React is a rich JavaScript library with a set of interactive and useful features required for creating large scale applications, developers do not enjoy what they can have in a fully featured framework such as Angular (another popular JS Framework). If you look at the MVC (Model View Controller) architecture, React only handles the view part. For Controller and Model you need additional libraries, and tools. This can result in poor structure of code, and its patterns. Whereas frameworks like Angular provide the complete MVC featured ground, which is more structured, and well managed.  This all sounds like jQuery again. When we talk about empowering JavaScript to structure like we do our code at backend, arguably you might be looking for a full featured, well-structured tool where similar practices and patterns are followed globally, and this is where React might not be very helpful. If not careful, you might end up having the same problem which React claims to resolve. It needs a quite deeper understanding of JavaScript and its core behaviors to make React work the way you want it to. Whereas working with Frameworks like Angular (although it is more difficult to learn than React) force developers to follow a strict structure where you enjoy similar patterns as backend development.4. Poor DocumentationSince React is changing so fast, new tools and patterns are adding up every now and then, and it is becoming difficult for the community to maintain the documentation. This makes it difficult to work with for new developers who want to start with React. Lack of poor documentation can also result in slower development among teams with less experienced developers. 5. JSXReact has introduced JSX to work with html, and JavaScript. This is like JavaScript and html syntax, and allows to mix html and JavaScript together but has some new attributes and syntaxes, which makes it difficult to work with when you start with React. For example, while working with class attribute, in JSX it becomes className. Also, the lack of rich documentation makes it more difficult to work with JSX.  This is what a JSX looks like while creating a simple login form. <form>    < h1 > Header {this.state.content} </h1>    <p> Enter your username: </p>    <input      className='form-control'      type='text'      onChange={this.userNameHandler}    />    <p> Enter your password: </p>    <input      className='form-control'      type='password'      onChange={this.passwordHandler}    />    <button      className='form-control'      type='submit'      onClick={this.submitHandler}    />  </form> 6. SEO HandlingIf you are building an application in React which is SEO (Search Engine Optimization) sensitive where the popularity of your application, its appearance and ranking in Google search results are priorities, then this, although not proven, is a concern. The concern is about ability of search engine crawlers to list dynamically loaded content. There are tools available to test your app for SEO results and rankings.Pros from Developer’s Perspective Easy to Learn: The biggest advantage that React has from the developer’s perspective, which is also the reason behind React getting more popular than other JavaScript libraries and frameworks, is that it is very easy to begin with. Anyone with basic understanding of HTML and JavaScript can quickly get started with React. Even though it has JSX to mix JavaScript and HTML together which is bit unconventional, it hasn’t stopped React from becoming the most loved JavaScript library among developers.  Structural Flexibility Unlike other conventional frameworks, React doesn’t draw boundaries on how a developer should treat code. This gives React developers freedom to express their own architectural styles to build apps. Developers who like to work with vanilla JavaScript love this flexibility as they are not used to the idea of a framework controlling the structure of code in an application. Pros from Business Owner’s Perspective One framework for all Platforms Most of the technology stacks force the use of different tools, language or frameworks for web and mobile app development. This requires business owners to hire developers of different skill sets for web and mobile app development, increasing the cost of app development and maintenance in the long run. With React, the easier learning curve allows a React web developer to quickly start with React Native, which is a mobile development framework based on React. This reduces the cost of hiring developers of multiple skill sets and also reduces the cost of maintenance, as the same technology is being used at both the platforms. Rapid Development Time is another significant factor when it comes to software development, as it directly impacts the cost of project development. React is easy to get started with, and has the structural flexibility that allows developers to do rapid application development, reducing both the time and cost of software development. This not only applies to web but mobile development as well. There are many businesses who had to choose between web and mobile apps while in their initial phases because of time and cost constraints. React has been able to give the confidence to start with mobile and web app development simultaneously, allowing them to reach a lot more customers than they would have had if they had to choose between web and mobile. Conclusion Honestly, there is no solid conclusion on whether these pros or cons can be summed up to decide if you should or should not go with React. It entirely depends on customer needs, domain needs and expertise in your team. With the right team of experts React can be implemented at its best, overcoming its cons like “rapid change or lack of documentation and lack of convention”. A team of expert developers can agree to follow a convention, document the practices and patterns they are following for any future developers who might join their team. With all these covered, React has a number of advantages including “Hight performance using Virtual DOM, State Management using Redux”, which you can use to make the best of web and mobile apps available today.

What are the Pros and Cons of React

6K
What are the Pros and Cons of React

If you are a web developer, you are a JavaScript developer--by choice or by force. I mention by force because not many web developers like to work with vanilla JavaScript, especially ones who have worked with frameworks and languages where Object Oriented concepts are made easier for developers to work with. But this does not stop JavaScript from becoming the most widely used language in the world. The popularity of JavaScript has been growing rapidly over the past years 

For any web development, lot of the work gets done by JavaScript at the user’s browser and at times it becomes difficult to manage vanilla JavaScript in large applications as it lacks the structure which developers enjoy in languages like Java, C# at the back end. 

Technology leaders identified this problem, and they came up with multiple solutions to make JavaScript not just easier to work with but also to give it performance boost and empowering browsers to do lot more without having to worry about managing complex state of applications as they grow to meet customer demand. React is one such solution along with Angular and Vue. 

What is React JS? 

ReactJS is a component-based JavaScript library created by FacebookReact makes it easier to create interactive UI using components and efficiently manage states of those components. Multiple components can be composed together to make complex applications without losing their state in DOM.  

Even though we are talking about React as a tool for web application here, it can also be used for mobile application development with React Native, a powerful and open-source native library for mobile application. 

This is how a simple React component looks like. 

classHelloWorldextendsReact.Component { 
  render() { 
    return ( 
      <div> 
        Hello world! 
      </div> 
    ); 
  } 
} 

What can we build using React JS? 

Being one of the most popular JavaScript libraries, React can be used to create anything you see on the web. It can be used for multiple requirements; be it a simple but interactive app like Instagram, or a complex streaming app with large userbase and support for multiple languages and regions like Netflix or an application like Facebook, with very large dataset and high complexity with the power to process more than a billion users’ requests parallelly. 

However, it is not just limited to highly scalable web applicationsand you can also create mobile applications using React Native which is an open-source mobile application framework. You can create Android, iOS and Windows apps using this framework. In fact, the above-mentioned web applications “Instagram, Facebook, Netflix” mobile apps are also created using React Native. It gives developers a rich library to utilize the native features of a device to deliver high performance and highly interactive applications to users across the world. 

Pros 

1. Component based architecture

It is not uncommon for vanilla JavaScript based apps to get into a stage, when managing state of data at user’s browser becomes a headache for developers. As the data and complexity of an application grow, it becomes difficult to maintain using vanilla JavaScript. 

The introduction of React componentbrings highly sophisticated unit of a web page which can be independently created, maintained, and even reused. You can divide your web page into multiple components, and they can work independently. You can update one of them without having to worry about changes in others. This makes it very loosely coupled and at the same time available for working together by merging with other components to bring out the best of the web application’s abilities. 

This is not something unique in React library. In fact, components are the basic building blocks in the Angular framework as welland a similar concept has been there in many MVC frameworks since a long time. 

2. High Performance

With component-based architectureReact allows to create highly scaled Single Page Application or SPA, in which content is dynamically loaded during user interaction without loading the entire page. However, this can turn into a trap. Imagine having to update DOM for every change caused by user’s interaction on web page. Every action might force DOM (which is a tree structure) to refresh itself. And if your web page is complex, having multiple UI components this can cause massive performance blockage. 

To solve thisReact uses the concept of Virtual DOM, which you can think of as copy of your real DOM. Now all the changes caused by user’s interaction or other events are handled by the virtual DOM first, and only if it (the intelligence of React) thinks it is important enough to refresh the real DOM, the real DOM is refreshed. This saves us from massively repeating recreation of the DOM tree for every trivial change resulting in high performance application.

3. Redux

Back to our SPA (Single Page Application), where there are multiple components sitting on one page and updated dynamically without reloading the entire page. Now all this sounds very simple and smooth. Which it is, until your components start talking to each other. Let’s say you have a web page where there are few form components which contains large forms with lot of controls, few table components, and a sidebar and header, footer. Content in tables must be updated when user submits form or part of formsAlso, you might want to update header when new record is created. Now here, our table components have dependency on form components. These dependencies, along with communication between them can grow as your application grows. 

All this can make our data unstable as there is no way to know which data is latest or which is correct. There is no single source of data. This can cause poor user experience and also performance issues. 

To make sure that all your components are in sync with latest data, we need to have a--let’s just call it-- manager who manages our dataand provides a single trustworthy source which makes sure the data which the components have is correct and truthful. This manager and its team are known as Redux in React.  

Redux forces components to avoid talking to each other directly or being dependent on each other, instead components send their data to redux and it is the responsibility of redux to update the components (which need those data) with new data. This way components are always updated with the latest data available without having to depend on each other.

4. Easy to Learn

This is another pro of working with React as any developer with understanding of html and JavaScript can start learning React. Unlike other JS frameworks like Angular which introduce lot of new terminologies, React uses most of what is already available. This makes it very easy to start with--another reason why it has grown to be the most popular JS library.  

It provides more flexibility (which it derives from Vanilla JavaScript) and does not force developers to follow any specific pattern like MVC or any other architectural pattern. Development teams are free to choose their own style or patterns while working with an application. This allows vanilla JavaScript developers to work with component-based architecture without having to lose the freedom they enjoyed with vanilla JavaScript. 

5. Mobile App Development

In a world where every platform, and every stack of an application requires you to learn a whole new tool or language or frameworks; React brings us the flexibility of using the same library over web and mobile applications. React Native allows us to create mobile applications on any mobile platform with the same React concepts and syntaxes. React Native helps you create interactive and high-performance mobile apps for any mobile device without having to learn new tool or language. 

So far, we talked about what makes React so popular among development teams, but every technology has pros and cons. Let’s talk about why many teams are not willing to work with React and what makes it less reliable when you need a well-structured and stable JS library to work with. 

Cons  

1. High Pace of Development

This is arguably the most discussed con of using React. React is not just rapidly growing library, it is also rapidly changing, which forces its developers to update the way they write code. Now this is obviously annoying for most of the developers who are not comfortable with adopting new ways every Monday they start or the ones who are working on an application where changes are critical to customers. There are many industries which are critical to change where customers look for more stable tools and technologies. But this again depends on how expert team members are and if they can convince their customers to trust them with React.  

2. Flexibility and Lack of Conventions

Yes, you read it right. I know that we discussed it as an advantage of using React, but at the same time it is also a disadvantage in a broader sense. Libraries, languages, or frameworks have their global standards of how developers work with them, and what styles or patterns they follow. This is useful because when developers change teams, they have an idea of what patterns or styles the new team might be following; whereas among React development teams it is not easy to predict what styles or standards a team might follow, making it harder for new developers to work with new teams and their standards. Developers who have worked with frameworks which follow a fixed structure and set of conventions might not find React very attractive to work with. 

3. Not a full-featured framework

Even though React is a rich JavaScript library with set of interactive and useful features required for creating large scale applications, developers do noenjoy what they can have in a fully featured framework such as Angular (another popular JS Framework). If you look at the MVC (Model View Controller) architecture, React only handles the view part. For Controller and Model you need additional libraries, and tools. This can result in poor structure of code, and its patterns. Whereas frameworks like Angular provide the complete MVC featured ground, which is more structured, and well managed.  

This all sounds like jQuery again. When we talk about empowering JavaScript to structure like we do our code at backend, arguably you might be looking for a full featured, well-structured tool where similar practices and patterns are followed globally, and this is where React might not be very helpful. If not careful, you might end up having the same problem which React claims to resolve. It needs a quite deeper understanding of JavaScript and its core behaviors to make React work the way you want it to. Whereas working with Frameworks like Angular (although it is more difficult to learn than React) force developers to follow strict structure where you enjoy similar patterns as backend development.

4. Poor Documentation

Since React is changing so fast, new tools and patterns are adding up every now and then, and it is becoming difficult for the community to maintain the documentation. This makes it difficult to work with for new developers who want to start with React. Lack of poor documentation can also result in slower development among teams with less experienced developers. 

5. JSX

React has introduced JSX to work with html, and JavaScript. This is like JavaScript and html syntax, and allows to mix html and JavaScript together but has some new attributes and syntaxes, which makes it difficult to work with when you start with React. For example, while working with class attribute, in JSX it becomes className. Also, the lack of rich documentation makes it more difficult to work with JSX.  

This is what a JSX looks like while creating a simple login form. 

<form> 
  h1 > Header {this.state.content} </h1> 
  <p> Enter your username: </p> 
  <input 
    className='form-control' 
    type='text' 
    onChange={this.userNameHandler} 
  /> 
  <p> Enter your password: </p> 
  <input 
    className='form-control' 
    type='password' 
    onChange={this.passwordHandler} 
  /> 
  <button 
    className='form-control' 
    type='submit' 
    onClick={this.submitHandler} 
  /> 
</form> 

6. SEO Handling

If you are building an application in React which is SEO (Search Engine Optimization) sensitive where the popularity of your application, its appearance and ranking in Google search results are priorities, then this, although not proven, is concern. The concern is about ability of search engine crawlers to list dynamically loaded content. There are tools available to test your app for SEO results and rankings.

Pros from Developer’s Perspective 

  1. Easy to Learn: The biggest advantage that React has from the developer’s perspective, which is also the reason behind React getting more popular than other JavaScript libraries and frameworks, is that it is very easy to begin with. Anyone with basic understanding of HTML and JavaScript can quickly get started with React. Even though it has JSX to mix JavaScript and HTML together which is bit unconventional, it hasn’t stopped React from becoming the most loved JavaScript library among developers. 
  2.  Structural Flexibility Unlike other conventional frameworks, React doesn’t draw boundaries on how a developer should treat code. This gives React developers freedom to express their own architectural styles to build apps. Developers who like to work with vanilla JavaScript love this flexibility as they are not used to the idea of a framework controlling the structure of code in an application. 

Pros from Business Owner’s Perspective 

  1. One framework for all Platforms Most of the technology stacks force the use of different tools, language or frameworks for web and mobile app development. This requires business owners to hire developers of different skill sets for web and mobile app development, increasing the cost of app development and maintenance in the long run. With React, the easier learning curve allows a React web developer to quickly start with React Native, which is a mobile development framework based on React. This reduces the cost of hiring developers of multiple skill setand also reduces the cost of maintenanceas the same technology is being used at both the platforms. 
  2. Rapid Development Time is another significant factor when it comes to software development, as it directly impacts the cost of project development. React is easy to get started with, and has the structural flexibility that allows developers to do rapid application development, reducing both the time and cost of software development. This not only applies to web but mobile development as well. There are many businesses who had to choose between web and mobile apps while in their initial phases because of time and cost constraints. React has been able to give the confidence to start with mobile and web app development simultaneouslyallowing them to reach a lot more customers than they would have had if they had to choose between web and mobile. 

Conclusion 

Honestly, there is no solid conclusion on whether these pros or cons can be summed up to decide if you should or should not go with React. It entirely depends on customer needs, domain needs and expertise in your team. With the right team of experts React can be implemented at its best, overcoming its cons like “rapid change or lack of documentation and lack of convention”. A team of expert developers can agree to follow a convention, document the practices and patterns they are following for any future developers who might join their team. With all these covered, React has number of advantages including “Hight performance using Virtual DOM, State Management using Redux”, which you can use to make the best of web and mobile apps available today.

Dheeraj

Dheeraj Kumar

Author

Dheeraj is a Full Stack Developer, Trainer and Architect. He has more than 8 years of experience with .NET and JavaScript stacks building enterprise applications. He has trained more than 1000 students and professionals in .Net, MEAN and MERN stack.

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. 
6796
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