Search

What Are React Keys?

We Love Lists:In React, lists are in the form of arrays in JavaScript which can store multiple values of the same data type. The general need to render lists of items in applications, whether they are web or mobile apps, is because the lists help in displaying the data in the ordered format. This is also mostly used to display the menus on the websites. In other words, lists focus on the UI part of the website, and are mainly used in displaying the menus on a website. Some examples of lists in a website are the navbar menu, sidebar menu etc.In Normal JavaScriptIn the normal JavaScript, the map () function is used to transverse the lists. In the code given below, the map () function is used to take the array of numbers and then multiply the elements of an array with 3. Here we declare a new array variable tripled, assign the new array values that are returned by the map () function and then log it.Codeconst number = [2, 4, 5, 3];  const tripled = number.map((num) => num * 3);  console.log(tripled) Output : [6, 12, 15, 9]Lists in ReactWhile creating a list in React, the map() function is used to traverse the list elements and for updating the content in the lists. We use curly braces {} while working with lists in React.The output obtained through the map() function is assigned to the listItem. We specify the order nature of the list in the output and return a <li> element for each item in the list. Finally, we render the React-DOM and obtain the result using the <ul> format at the end. Here’s what the code looks like:Index.jsimport React from 'react';      import ReactDOM from 'react-dom';      import reportWebVitals from './reportWebVitals';  // declaring the constants  const myList = [1, 2, 3, 4, 5];      const listItems = myList.map((myList)=>{      return <div><li>{myList}</li></div>;      });      // rendering using the ReactDOM, render() function  ReactDOM.render(      <ul> {listItems} </ul>,      document.getElementById('root')     );  reportWebVitals();OutputThe line ReactDom.render() method is used to render a React element into the DOM in the supplied container and returns a reference to the component. In this, we are importing any App.js file or any Index.html file for rendering the pages. In the above example we are declaring variables and using the function in the same file itself using the root element.Instead, we are using the “root” to point out the elements present in the index.ex.js file itself. The “root” element is the supplied container in DOM, and <ul>ListItem</ul> is the component. The root helps to auto render into the documents where it consists of Listelements to be printed out onto the console.How not to render ListIn the above example, we have initialized the list and rendered it using the map() function. We cannot render the list without using the “key” component. If we do so, we may get the output, but we may have some errors in the console. Consider the above example, which is coded without using the key component. In this case we have got the output, but the console has resulted in some warnings. So, it is suggested not to list the components in a program without the key component to uniquely identify the elements in the given list of elements.OutputWhat is the 'key' attribute?In React, keys are like a Special String attribute that is included in the Creation of List of Elements. Keys play a great significance in React, and they help us to know what are the items in the given list of elements that have changed or are updated or removed. In simple words, the keys help in providing the identity to the elements in the Lists. Keys help to uniquely identify the elements in the Lists.Syntax for Initialization of a KeyIn general, the keys are declared using a flower brace “{}”, and in the braces the corresponding functionality is added to get the output of the program. Keys should be given to the elements that are present inside the array, to provide a stable entity to the elements. To pick the right key from the list, the element should be uniquely identified among the elements in the list.Syntax: -   key = { }How should a key be chosen?It is recommended to choose a STRING as a key, that identifies the items uniquely in a given list. If the given list contains the variable values as strings, and those strings are said to be unique, then the corresponding values can be taken as a KEY. Else if the given list doesn’t contain Strings for variable values, the corresponding variable is type-casted explicitly to strings and then used in the program.By considering the problem encountered in the previous example, we try to remove the warnings using the Key attribute in the above program. After using the key attribute in the above example, we found there are no errors in the console, when we inspected the web page source. In this way the Key attribute is helpful to us in overcoming the errors in the creation of lists in React. The console is illustrated as below:Example of using keyLists.jsimport React from 'react'; // creating a function function Lists(){     const numbers = [1,2,3,4,5]     const listItems = numbers.map((number) =>  <li         key={number.toString()}>{number}</li>)     return <div><ul>{listItems}</ul></div> } export default Lists;App.jsimport './App.css'; import Lists from './Lists'; import React from 'react'; // Defining the class named “App” class App extends React.Component {   render() {     return (       <div className = "ml-2">         <h4>Usage of Keys resulted no Errors!</h4>       <Lists />         </div>     )   } } export default App;OutputGenerally, the Key is used to identify the elements in a list uniquely. For the unique identification, we can use some alternatives like “id” or “index” forms as Keys from our data.Accessing Key element using ID formLists.jsimport React from 'react'; // Creating the function using function keyword in react function Lists(){     const stringLists = [ 'upgrad', 'knowledge', 'Hut', 'Blog', 'Writing'];         const updatedLists = stringLists.map((strList)=>             <li key={strList.id}> {strList} </li>)           return <div><ul>{updatedLists}</ul></div>   } export default Lists;App.jsimport './App.css'; import Lists from './Lists'; import React from 'react'; // the class Name is defined here “App” class App extends React.Component {   render() {     return (       <div className = "ml-2">         <h4>Usage of ID Form </h4>       <Lists />         </div>     )   } } export default App;OutputWhen we don’t have stable IDs for rendering of items, we use the item Index as the Key to access the elements in the list.Accessing Key Element using Index FormLists.jsLists.jsimport React from 'react'; // defining the function function Lists(){     const stringLists = [ 'bombay', 'delhi', 'calcutta' ];         const updatedLists = stringLists.map((strList, index)=>             <li key={index}> {strList} </li>)           return <div><ul>{updatedLists}</ul></div>   } export default Lists;App.jsimport './App.css'; import Lists from './Lists'; import React from 'react';  // class Name is defined here class App extends React.Component {   render() {     return (       <div className = "ml-2">         <h4>Usage of INDEX Form </h4>       <Lists />         </div>     )   } } export default App;OutputIt is not recommended to use the Indexes for the KEYS, if there is change in the order of items. That action sometimes may result in negative performance and could cause some issues with the Component State.Usage of Keys with ComponentKeys are generally used to identify the unique element in the given list of elements. But, the usage of keys while mapping to the elements describes a particular order. Assigning of keys creates an order and structure that leads to the correct implementation. For example, let us imagine we have created ListItem as a separate component and that ListItem is used for extraction of elements in the list of elements. In this case we should assign the Key component to the <ListItem /> in the given array of elements but not to the <li /> component present in the ListItem itself.  Example of Incorrect Key usage with ComponentIndex.jsimport React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import reportWebVitals from './reportWebVitals'; function ListItem(props) {     const item = props.item;     return (       // Wrong Usage     <li key={item.toString()}>         {item}       </li>     );   }   function NameList(props) {     const myLists = props.myLists;     const listItems = myLists.map((strLists) =>       // Key should be used here     <ListItem item={strLists} />     );   return (       <div>           <h2>Incorrect Key Usage Example</h2>                 <ol>{listItems}</ol>       </div>     );   }   const myLists = ['csk', 'rcb', 'mi', 'srh', 'kkr', 'dd'];   ReactDOM.render(     <NameList myLists={myLists}/>,     document.getElementById('root')   ) reportWebVitals();index.html<!DOCTYPE html> <html lang="en"> <head>   <meta charset="UTF-8">   <meta name="viewport" content="width=device-width, initial-scale=1.0">   <meta http-equiv="X-UA-Compatible" content="ie=edge">   <title>REACT TEST</title> </head>  <body>   <div id="root"></div>   <script src="./index.js"></script> </body> </html>OutputExample of Correct Key usage with Componentindex.jsimport React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import reportWebVitals from './reportWebVitals'; function ListItem(props) {     const item = props.item;     return (       // key is not written here       <li> {item} </li>     );   }   function NameList(props) {     const myLists = props.myLists;     const listItems = myLists.map((strLists) =>       // Key is written here       <ListItem key={myLists.toString()} item={strLists} />     );     return (       <div>           <h2>Correct Key Usage Example</h2>               <ol>{listItems}</ol>       </div>     );   }    const myLists = ['HYD', 'MYS', 'AP', 'GOA'];    ReactDOM.render(     <NameList myLists={myLists}/>,     document.getElementById('root')   ) reportWebVitals();index.html<!DOCTYPE html> <html lang="en">  <head>   <meta charset="UTF-8">   <meta name="viewport" content="width=device-width, initial-scale=1.0">   <meta http-equiv="X-UA-Compatible" content="ie=edge">   <title>REACT TEST</title> </head>  <body>   <div id="root"></div>   <script src="./index.js"></script> </body>  </html>OutputWhile working with usage of Key with Component, we mostly work on two files namely the JavaScript file (“index.js”) and the HTML file (“index.html”). At this time, we don’t have any work to do with the App.js file, so we comment out the code lines in the file and work only on the index JavaScript and HTML files.The usage of keys in both the examples demonstrated above results in a similar output. But if there is any incorrect usage of keys, we come across errors in the corresponding HTML page on inspection. If the key is used correctly, there will not be any errors if we inspect the page.Keys Uniqueness among its SiblingsWe had learnt that the key should be unique among all the elements in the given list of elements i.e., it should be unique among the siblings in the given list. It is not compulsory that the keys initialized in the program should be Globally unique. We will try to produce two different arrays using the same set of keys as demonstrated below:Index.jsimport React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import reportWebVitals from './reportWebVitals';  function TourBlog(props) {     const place = (       <ol>         {props.data.map((show) =>           <li key={show.id}>             {show.title}           </li>         )}       </ol>     );     const famousfor = props.data.map((show) =>       <div key={show.id}>         <h3>{show.title}: {show.content}</h3>           </div>     );     return (       <div>         {place}         <hr />         {famousfor}       </div>     );   }   const data = [     {id: 1, title: 'Goa', content: 'Famous For Beaches.....!!'},     {id: 2, title: 'Mumbai', content: 'Famous For Street Food.........!!'},     {id: 3, title: 'Manali', content: 'Famous for Valleys & Beautiful Scenaries....!!'}   ];   ReactDOM.render(     <TourBlog data={data} />,     document.getElementById('root')   );   reportWebVitals();index.html<!DOCTYPE html> <html lang="en">  <head>   <meta charset="UTF-8">   <meta name="viewport" content="width=device-width, initial-scale=1.0">   <meta http-equiv="X-UA-Compatible" content="ie=edge">   <title>REACT TEST</title> </head>  <body>   <div id="root"></div>   <script src="./index.js"></script> </body>  </html>OutputSummary To sum up what we have learnt in this article:A Key is a unique element among its siblings in the given list of elements.A Key is declared in array format. It takes the String format as a default state to bring the output from the list.If the given elements in the lists are not in the form of strings, they are type-casted into the string form and then accessed using the Key component in React.We can access the key elements using the Id and Index forms.We can use keys along with the Components. In this, we assign the Key component with the respective <ListItem> only, but not to the <li> component unless the particular item type is not specified in the given program.Finally, we have seen the usage of Key component with two types of arrays in the given program itself to generate the result at the end.

What Are React Keys?

5K
What Are React Keys?

We Love Lists:

In React, lists are in the form of arrays in JavaScript which can store multiple values of the same data type. The general need to render lists of items in applications, whether they are web or mobile apps, is because the lists help in displaying the data in the ordered format. This is also mostly used to display the menus on the websites. In other words, lists focus on the UI part of the website, and are mainly used in displaying the menus on a website. Some examples of lists in a website are the navbar menu, sidebar menu etc.

In Normal JavaScript

In the normal JavaScript, the map () function is used to transverse the lists. In the code given below, the map () function is used to take the array of numbers and then multiply the elements of an array with 3. Here we declare a new array variable tripled, assign the new array values that are returned by the map () function and then log it.

Code

const number = [2, 4, 5, 3]; 
const tripled = number.map((num) => num * 3); 
console.log(tripled) 

Output : [6, 12, 15, 9]

Lists in React

While creating a list in React, the map() function is used to traverse the list elements and for updating the content in the lists. We use curly braces {} while working with lists in React.

The output obtained through the map() function is assigned to the listItem. We specify the order nature of the list in the output and return a <li> element for each item in the list. Finally, we render the React-DOM and obtain the result using the <ul> format at the end. 

Here’s what the code looks like:

Index.js

import React from 'react';     
import ReactDOM from 'react-dom';     
import reportWebVitals from './reportWebVitals'; 
// declaring the constants 
const myList = [1, 2, 3, 4, 5];     
const listItems = myList.map((myList)=>{     
return <div><li>{myList}</li></div>;     
});     
// rendering using the ReactDOM, render() function 
ReactDOM.render(     
<ul> {listItems} </ul>,     
document.getElementById('root')    
); 
reportWebVitals();

Output

What Are React Keys?

The line ReactDom.render() method is used to render a React element into the DOM in the supplied container and returns a reference to the component. In this, we are importing any App.js file or any Index.html file for rendering the pages. In the above example we are declaring variables and using the function in the same file itself using the root element.

Instead, we are using the “root” to point out the elements present in the index.ex.js file itself. The “root” element is the supplied container in DOM, and <ul>ListItem</ul> is the component. The root helps to auto render into the documents where it consists of Listelements to be printed out onto the console.

How not to render List

In the above example, we have initialized the list and rendered it using the map() function. We cannot render the list without using the “key” component. If we do so, we may get the output, but we may have some errors in the console. Consider the above example, which is coded without using the key component. In this case we have got the output, but the console has resulted in some warnings. So, it is suggested not to list the components in a program without the key component to uniquely identify the elements in the given list of elements.

Output

What Are React Keys?What is the 'key' attribute?

In React, keys are like a Special String attribute that is included in the Creation of List of Elements. Keys play a great significance in React, and they help us to know what are the items in the given list of elements that have changed or are updated or removed. In simple words, the keys help in providing the identity to the elements in the Lists. Keys help to uniquely identify the elements in the Lists.

Syntax for Initialization of a Key

In general, the keys are declared using a flower brace “{}”, and in the braces the corresponding functionality is added to get the output of the program. Keys should be given to the elements that are present inside the array, to provide a stable entity to the elements. To pick the right key from the list, the element should be uniquely identified among the elements in the list.

Syntax: -   key = { }

How should a key be chosen?

It is recommended to choose a STRING as a key, that identifies the items uniquely in a given list. If the given list contains the variable values as strings, and those strings are said to be unique, then the corresponding values can be taken as a KEY. Else if the given list doesn’t contain Strings for variable values, the corresponding variable is type-casted explicitly to strings and then used in the program.

By considering the problem encountered in the previous example, we try to remove the warnings using the Key attribute in the above program. After using the key attribute in the above example, we found there are no errors in the console, when we inspected the web page source. In this way the Key attribute is helpful to us in overcoming the errors in the creation of lists in React. The console is illustrated as below:

Example of using key

Lists.js

import React from 'react';

// creating a function
function Lists(){
    const numbers = [1,2,3,4,5]
    const listItems = numbers.map((number) =>  <li         key={number.toString()}>{number}</li>)
    return <div><ul>{listItems}</ul></div>
}
export default Lists;

App.js

import './App.css';
import Lists from './Lists';
import React from 'react';

// Defining the class named “App”
class App extends React.Component {
  render() {
    return (
      <div className = "ml-2">
        <h4>Usage of Keys resulted no Errors!</h4>
      <Lists />  
      </div>
    )
  }
}
export default App;

Output

What Are React Keys?Generally, the Key is used to identify the elements in a list uniquely. For the unique identification, we can use some alternatives like “id” or “index” forms as Keys from our data.

Accessing Key element using ID form

Lists.js

import React from 'react';

// Creating the function using function keyword in react
function Lists(){
    const stringLists = [ 'upgrad', 'knowledge', 'Hut', 'Blog', 'Writing'];    
    const updatedLists = stringLists.map((strList)=>    
        <li key={strList.id}> {strList} </li>)  
        return <div><ul>{updatedLists}</ul></div>  

}
export default Lists;

App.js

import './App.css';
import Lists from './Lists';
import React from 'react';

// the class Name is defined here “App”
class App extends React.Component {
  render() {
    return (
      <div className = "ml-2">
        <h4>Usage of ID Form </h4>
      <Lists />  
      </div>
    )
  }
}
export default App;

Output

What Are React Keys?

When we don’t have stable IDs for rendering of items, we use the item Index as the Key to access the elements in the list.

Accessing Key Element using Index FormLists.js

Lists.js

import React from 'react';

// defining the function
function Lists(){
    const stringLists = [ 'bombay', 'delhi', 'calcutta' ];    
    const updatedLists = stringLists.map((strList, index)=>    
        <li key={index}> {strList} </li>)  
        return <div><ul>{updatedLists}</ul></div>
 
}
export default Lists;

App.js

import './App.css'; 
import Lists from './Lists'; 
import React from 'react'; 

// class Name is defined here 
class App extends React.Component { 
  render() { 
    return ( 
      <div className = "ml-2"> 
        <h4>Usage of INDEX Form </h4> 
      <Lists />   
      </div> 
    ) 
  } 
} 
export default App;

Output

What Are React Keys?

It is not recommended to use the Indexes for the KEYS, if there is change in the order of items. That action sometimes may result in negative performance and could cause some issues with the Component State.

Usage of Keys with Component

Keys are generally used to identify the unique element in the given list of elements. But, the usage of keys while mapping to the elements describes a particular order. Assigning of keys creates an order and structure that leads to the correct implementation. 

For example, let us imagine we have created ListItem as a separate component and that ListItem is used for extraction of elements in the list of elements. In this case we should assign the Key component to the <ListItem /> in the given array of elements but not to the <li /> component present in the ListItem itself.  

Example of Incorrect Key usage with Component

Index.js

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import reportWebVitals from './reportWebVitals';

function ListItem(props) {  
  const item = props.item;  
  return (  
    // Wrong Usage
    <li key={item.toString()}>  
      {item}  
    </li>  
  );  
}  

function NameList(props) {  
  const myLists = props.myLists;  
  const listItems = myLists.map((strLists) =>  
    // Key should be used here
    <ListItem item={strLists} />  
  );  

return (  
    <div>  
        <h2>Incorrect Key Usage Example</h2>  
              <ol>{listItems}</ol>  
    </div>  
  );  
}  

const myLists = ['csk', 'rcb', 'mi', 'srh', 'kkr', 'dd'];  

ReactDOM.render(  
  <NameList myLists={myLists}/>,  
  document.getElementById('root')  
)

reportWebVitals();

index.html

<!DOCTYPE html> 
<html lang="en">

<head> 
  <meta charset="UTF-8"> 
  <meta name="viewport" content="width=device-width, initial-scale=1.0"> 
  <meta http-equiv="X-UA-Compatible" content="ie=edge"> 
  <title>REACT TEST</title> 
</head> 

<body> 
  <div id="root"></div> 
  <script src="./index.js"></script> 
</body>

</html>

Output

What Are React Keys?

Example of Correct Key usage with Component

index.js

import React from 'react'; 
import ReactDOM from 'react-dom'; 
import './index.css'; 
import reportWebVitals from './reportWebVitals'; 
function ListItem(props) {   
  const item = props.item;   
  return (   
    // key is not written here   
    <li> {item} </li>   
  );   
}   
function NameList(props) {   
  const myLists = props.myLists;   
  const listItems = myLists.map((strLists) =>   
    // Key is written here   
    <ListItem key={myLists.toString()} item={strLists} />   
  );   
  return (   
    <div>   
        <h2>Correct Key Usage Example</h2>   
            <ol>{listItems}</ol>   
    </div>   
  );   
}   

const myLists = ['HYD', 'MYS', 'AP', 'GOA'];   

ReactDOM.render(   
  <NameList myLists={myLists}/>,   
  document.getElementById('root')   
) 
reportWebVitals();

index.html

<!DOCTYPE html> 
<html lang="en"> 

<head> 
  <meta charset="UTF-8"> 
  <meta name="viewport" content="width=device-width, initial-scale=1.0"> 
  <meta http-equiv="X-UA-Compatible" content="ie=edge"> 
  <title>REACT TEST</title> 
</head> 

<body> 
  <div id="root"></div> 
  <script src="./index.js"></script> 
</body> 

</html>

OutputWhat Are React Keys?

While working with usage of Key with Component, we mostly work on two files namely the JavaScript file (“index.js”) and the HTML file (“index.html”). At this time, we don’t have any work to do with the App.js file, so we comment out the code lines in the file and work only on the index JavaScript and HTML files.

The usage of keys in both the examples demonstrated above results in a similar output. But if there is any incorrect usage of keys, we come across errors in the corresponding HTML page on inspection. If the key is used correctly, there will not be any errors if we inspect the page.

Keys Uniqueness among its Siblings

We had learnt that the key should be unique among all the elements in the given list of elements i.e., it should be unique among the siblings in the given list. It is not compulsory that the keys initialized in the program should be Globally unique. We will try to produce two different arrays using the same set of keys as demonstrated below:

Index.js

import React from 'react'; 
import ReactDOM from 'react-dom'; 
import './index.css'; 
import reportWebVitals from './reportWebVitals'; 

function TourBlog(props) {   
  const place = (   
    <ol>   
      {props.data.map((show) =>   
        <li key={show.id}>   
          {show.title}   
        </li>   
      )}   
    </ol>   
  );   
  const famousfor = props.data.map((show) =>   
    <div key={show.id}>   
      <h3>{show.title}: {show.content}</h3>       
    </div>   
  );   
  return (   
    <div>   
      {place}   
      <hr />   
      {famousfor}   
    </div>   
  );   
}   
const data = [   
  {id: 1, title: 'Goa', content: 'Famous For Beaches.....!!'},   
  {id: 2, title: 'Mumbai', content: 'Famous For Street Food.........!!'},   
  {id: 3, title: 'Manali', content: 'Famous for Valleys & Beautiful Scenaries....!!'}   
];   
ReactDOM.render(   
  <TourBlog data={data} />,   
  document.getElementById('root')   
);   
reportWebVitals();

index.html

<!DOCTYPE html> 
<html lang="en"> 

<head> 
  <meta charset="UTF-8"> 
  <meta name="viewport" content="width=device-width, initial-scale=1.0"> 
  <meta http-equiv="X-UA-Compatible" content="ie=edge"> 
  <title>REACT TEST</title> 
</head> 

<body> 
  <div id="root"></div> 
  <script src="./index.js"></script> 
</body> 

</html>

OutputWhat Are React Keys?Summary 

To sum up what we have learnt in this article:

  • A Key is a unique element among its siblings in the given list of elements.
  • A Key is declared in array format. It takes the String format as a default state to bring the output from the list.
  • If the given elements in the lists are not in the form of strings, they are type-casted into the string form and then accessed using the Key component in React.

We can access the key elements using the Id and Index forms.

We can use keys along with the Components. In this, we assign the Key component with the respective <ListItem> only, but not to the <li> component unless the particular item type is not specified in the given program.

Finally, we have seen the usage of Key component with two types of arrays in the given program itself to generate the result at the end.


KnowledgeHut

KnowledgeHut

Author

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

Join the Discussion

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

Suggested Blogs

What Are the React Component Lifecycle Methods?

It's all about components!One of the reasons for the popularity of React is the concept of reusable web components, and we can  achieve this by using functional components.What this means is that the same component  can be reused with different  properties to display different  information.  In React, a component represents a part of the user interface.Functional components are named as such because you create them by writing function as shown below. In a functional component, all you need to do is return the JSX that you want this component to represent. A component code is usually placed in a JavaScript file. In React there are two component types  stateless functional componentstateful class component The functional components are literally JavaScript functions that return HTML which represents the UI. import React from "react" import ReactDOM from "react-dom" function TestApp() {     return (    < h1 >Code goes here   ) } ReactDOM.render(   ,   document.getElementById("root") )  }In the functional component you could pass props to the function itself and inside the code you can just say props.whatever as shown below:    function TestApp(props) {      return (       {props.whatever}      )  } As we go more deep into React, we are going to find that  functional components can’t do everything that we need them to do.So that is  where class components will help. Let’s see how we can convert the above functional component into a class-based component.  Class based components are basically es6 classes. Similar to a  functional component, a class component also can optionally receive props as input and return HTML. Apart from the props, a class component can also maintain a private internal state; as in, it can maintain some information which is private to that component. Basically if you need state or lifecycle methods,you will have to use class based component. All class based components are child classes for the Component class.In every class component at least one method is needed, that is the render method, and this class component is identical to the functional component as above.           import React from "react"  class TestApp extends React.Component {      render() {          return (                                < h1 >Code goes here                        )      }  }  export default TestApp With a class based component, any time we user props we need to use this.props as shown below: import React, {Component} from "react"  class TestApp extends React.Component {       someMethodHere() {              }        render() {          return (                                < h1 >{this.props.whatever}                        )      }  }   export default TestAppp Understanding Lifecycle:Every single component that we create is actually going to go through a series of phases during its lifecycle in the React application, when it is being rendered and updated. Lifecycle methods are divided into different parts. Let’s talk about the most important methods and commonly used ones. The first lifecycle method which is commonly used is render method and this is often not listed as lifecycle method.What this does, is to determine exactly what gets rendered to the screen; which in turn is how the component is displayed to the world. The render method can be called many times. Anytime React determines  that something changes  like states or props which might affect how the component is supposed to display, React may run the render method once again. render() {          return (                                Code goes here                        )      } Lifecycle Methods:React provides us with built-in methods that can be overridden at particular stages in the lifecycle.The Lifecycle methods available for class components are : Mounting Updating UnMounting Error Handling Mounting: The Mounting lifecycle method is called when an instance of a component is being created and inserted into a Document object model (DOM).There are four methods during the mounting phase: constructor Static  getDerivedstatefromprops Render ComponentDidmount Let’s see the order of execution  constructor ---- > Static  getDerivedstatefromprops ---  > render--- > ComponentDidmount import React, { Component } from “react”           Class TestApp extends  Component constructor(props) { super(props) this.state = { name = ‘Test app’  } console.log(‘TestApp’) } static getDerivedStateFromProps(props, state) { console.log(‘getDerivedStateFromProps') return null } componentDidMount() { console.log(‘componentDidMount') } render() { console.log(render')   return (   TestApp    ) }  } export default TestAppUpdating: The Updating lifecycle method is called when a component is being re-rendered as a result of changes to either its props or state. There are five methods during the updating  phase: Static  getDerivedstatefromprops shouldComponentUpdate Render getSnapshotBeforeUpdate componentDidUpdate The order of execution in this method is as below: constructor(props)-->Static  getDerivedstatefromprops -- >render-->getSnapshotBeforeUpdate → componentDidUpdate import React, { Component } from “react”           Class TestApp extends  Component constructor(props) { super(props); this.state = { name = ‘Test app’  } console.log(‘TestApp’) } static getDerivedStateFromProps(props, state) { console.log(‘getDerivedStateFromProps') return null } getSnapshotBeforeUpdate (prevProps, prevState) { console.log(‘getSnapshotBeforeUpdate’) } componentDidUpdate (prevProps, prevState, snapshot) { console.log(‘getSnapshotBeforeUpdate’) } render() { console.log(‘render')   return (   TestApp   )  }  } export default TestAppUnMounting: The UnMounting lifecycle method is called when a component is removed from DOM.There is only one method during the UnMounting  phase: component will unmount Let’s see the order of execution in this method: import React, { Component } from “react”           Class TestApp extends  Component constructor(props) { super(props); this.state = { name = ‘Test app’  } console.log(‘TestApp’) } componentWillUnmount() { console.log(‘componentWillUnmount’)  } render() { console.log(‘render')   return (     TestApp   ) } } export default TestAppError Handling:The Error Handling  lifecycle method is called when there is an error during rendering in a lifecycle method.There are two methods during the UnMounting  phase:StaticgetDerivedstatefromErrorcomponentDidCatchLet’s see the order of execution in this method:constructor(props) -------------- > StaticgetDerivedstatefromError-- > componentDidCatchimport React, { Component } from “react”           Class TestApp extends  Component constructor(props) { super(props); this.state = { hasError: false} console.log(‘TestApp’) } static getDerivedStateFromError(error) { return { hasError: true };  } componentDidCatch(error, errorInfo) { errorService.log({ error, errorInfo });  } render() { console.log(‘render')   return (     TestApp    ) } } export default TestAppcomponentDidMount:This is one of the methods of the mounting phase and is defined in the same way as any other method inside the class. This essentially is like saying  “you were just born”, and in reality this component did just mount to the screen.The very first time the component shows up, React will run the componentDidMount method. The most common use case for componentDidMount is to do something like an API call when we need to get data from some kind of external source.  For example, let’s assume that the below component is a list of names, and I need to get it from an external source database or some server before  I am able to accurately display the list of names. As soon as the component finishes mounting,we can get the data that we need to display.import React, {Component} from "react" class ListOfNames extends Component { super() this.state = {} } componentDidMount() { // Get the data which is list of names to display it correctly    }   render() { return ( Code goes here  ) }  } export default ListOfNamescomponentDidUpdate : This is one of methods in the updating phase.When a parent passes its state down through props, and then the state changes, React passes the updated value down through props to the component and re-renders that component so it can correctly display according to the updated props it is receiving. Inside componentDidUpdate we can do some more things, based on that change of props if we'd like.For example, if this component were receiving props that it used to make an API call, and the new incoming props would require the component to make another API call to a different endpoint, componentDidUpdate allows us to check if that prop is the thing that changed and make the API call if so.Since componentDidUpdate is coming from the superclass Component, we don't need to bind it to our own component. This is true of any of the pre-built lifecycle methods like componentDidMount too.Below componentDidUpdate will get prevProps and prevProps,  as the update has already happened. The old state is the current state, so we don't have an upcoming state or props.import React, {Component} from "react" class ListOfNames extends Component { constructor() { super() this.state = {} componentDidUpdate(prevProps, prevState) { console.log(“componentDidUpdate”,prevProps,prevState); } render() { return ( Code goes here ) } } export default ListOfNamesshouldComponentUpdate() : This is also one of the methods in the updating phase which gives us a chance to optimize the application. We can implement some  logic inside this method that allows the component to determine whether or not it's important to even think about updating.To help make that decision the shouldComponentUpdate method is going to  receive the incoming props and the incoming state which will call nextProps and nextState as below.  In the below shouldComponentUpdate return true if you want to update or return false if you don’t want to update. This return false from  shouldComponentUpdate will make the application more performant.import React, {Component} from "react" class ListOfNames extends Component { constructor() { super() this.state = {} shouldComponentUpdate(nextProps, nextState) { // or return false  if not to update   } render() { return ( div> Code goes here )  } } export default ListOfNames Summary:In this blog,we talked about two different kinds of components, functional and a class component, and what each one of those is capable of. Basically if you need state or lifecycle methods, you will have to use class-based components; otherwise it's a good practice to use functional components. We talked about props which are the primary way to pass data down to the component tree and also talked about a state which allows your component to hold on to and modify the data.
5355
What Are the React Component Lifecycle Methods?

It's all about components!One of the reasons for t... Read More

How Is a Node.JS Child Process Launched?

There is a high probability that you have already heard or read somewhere that Node.js is single-threaded. Although it is true, there is some nuance to this statement. In this article let’s quickly look at the threading architecture in Node.js, understand its limitations and also discuss four different techniques through which we could overcome those limitations.The Nuance with Node.js and Threads:JavaScript is a single-threaded language and since Node.js is more of an environment to run JavaScript outside of a browser, we could say that Node.js is also single-threaded.But, it is crucial to understand that while the code we write runs on a single thread with an event loop in the same thread, certain operations performed by some Node libraries that interact with the underlying operating system might use a multi-threaded approach.For instance, the crypto library in Node uses the libuv library internally, which is written in C, and libuv has access to a thread pool. Hence the operations performed by the crypto library may be executed in a multithreaded fashion.The Limitations With Node.js:Because our code runs on a single thread, CPU-intensive actions in our code logic will block the event thread; thereby increasing the server latency and reducing its throughput.An example of a CPU-intensive task could be parsing a huge Excel sheet, manipulating the data from it and writing the results to a new sheet.Typically, Node.js is not the preferred tool to do such jobs. But let’s say that we have some tech stack limitations and can only use Node. Then, we’ll have to find a way to make sure that this computationally heavy process doesn’t stall our thread.Some Workarounds to Tackle the Single-threaded Nature:The most common approach is to resort to multiprocessing using the cluster library in Node. A second common approach is a multi-threading approach using worker threads.In this article, we’ll be looking at various ways to resort to a multiprocessing approach. We won’t be discussing the cluster module but will be having a look at the fork method from the `child_process` module in Node, which the cluster module uses internally to achieve multiprocessing.The `child_process` module makes it possible to spawn subprocesses from the main process. All the spawned subprocesses, by default will have pipes established with the main process for the standard streams namely: `stdout`, `stdin` and `stderr`.The Various APIs for Multiprocessing in Node Child_process module:Node handles multiprocessing through a module named `child_process` and as the name suggests, it spawns child processes from the main process. The following are the four different ways to create child processes using the module:spawn()exec()execFile() andfork()We will briefly discuss how these four methods work and the differences between them.Spawn:Spawn is a function exported by the `child_process` module, so we could use it in our code in the following way:const {spawn} = require('child_process');   const lsCommand = spawn('ls');The spawn method, when invoked, creates a child process and runs the command which is passed as the first parameter to the spawn function in the created process. In the example above, the `ls` command which is used to list all files and directories on a Linux machine, will be run on the new child process.Optionally, spawn also accepts a second parameter which is an array of arguments to the passed command. By default, it will be an empty array.Let’s assume that we need to display the hidden files as well. In this case, we usually pass the `-a` switch to the `ls` command. We can do that through the spawn function as follows:const lsCommand = spawn('ls',['-a']);It is interesting to note that the new child process instance created by spawn implements the EventEmitter API and hence we can attach listeners for different events on various streams such as stdin , stdout and stderr.In the following code snippet, let’s look at how we could attach listeners to the data event on the stdout stream in a process created by the  spawn function:const {spawn} = require('child_process');   const lsCommand = spawn('ls', ['-a']);   console.log(`main process id: ${process.pid}`); console.log(`spawned child process id: ${lsCommand.pid}`);   lsCommand.stdout.on('data',(data)=>console.log(`Output from spawned child process with id ${lsCommand.pid}:\n ${data}`));The execution of the above snippet will be as follows:Exec:The exec function also creates a child process. However, unlike the spawn function, it creates a shell first and then runs the command provided to it as the first argument.The first argument could be a command or a location to a script file that you would like to be executed in the spawned shell in the child process.We could use a callback as a second argument, that buffers the output of the executed command from the standard output (stdout) and the stand error (stderr) streams.Let’s look at a code snippet with exec():const { exec } = require('child_process');   const execCallback = (error, stdout, stderr)=>{   if (error) {     console.error(`exec error: ${error}`);     return;   }   console.log(`standard output: ${stdout}`);   console.log(`standard error: ${stderr}`); }   const catCommand = exec('cat spawn-demo.js | wc -w', execCallback); console.log(`Main Process Id: ${process.pid}`); console.log(`child process Id: ${catCommand.pid}`);As we can see from the code snippet above, since the command we pass to exec will be run on a shell we could use shell pipes `|` to combine multiple commands. In the above code example, we can print the content of spawn-demo.js file and count the number of words in the output.ExecFile:The execFile function differs from exec function in the way that it does not create a shell on which to run the supplied command. Hence, we could use this as an option if we would like to execute some background scripts without blocking our applications thread.Let’s assume that we have a demo bash script file named `versions.sh` as follows:# versions.sh #!/bin/bash echo "printing different software versions" echo "node version:  $(node -v)" echo "npm version: $(npm -v)" echo "script run complete"Now, we can use the execFile function to run this script on a separate child process without creating a shell as follows:const {execFile} = require('child_process');   const versionsScriptRunner = execFile('./versions.sh',(err,stdout)=>{   if(err){     console.log("script file failed to be executed");     return;   }   console.log(stdout); });When we run the above snippet, the output will be as follows:Fork:The fork function is very similar to the spawn function except for the difference that when fork is used, the created child process will have an IPC (Inter-Process Communication) channel established with the parent process. Thus, we could use this method for use cases where we require a bi-directional communication channel between the parent and the child processes. Let’s have a timer file as follows://timer.js       let seconds = 0;     setInterval(()=>{    process.send({seconds:`${++seconds} form pid ${process.pid}`});   },1000);     process.on('message',msg=>{    console.log('from parent process',msg);   });Now, we’ll create a child process with the fork method and run the timer.js file on the forked process as follows:const { fork } = require('child_process');   const forkedProcess = fork('timer.js');   forkedProcess.on('message', (msg) => {   console.log('Message from child', msg); });   forkedProcess.send({ message: `This is from parent pid: ${process.pid}` })The above code snippets demonstrate the IPC channel between the parent and child processes:The Comparison:CriteriaSpawnExecExecFileForkCreation of a new shell on child-process instantiationBy default, a shell is not spawned to execute the given command.By default, a shell is spawned and the given command is executed on it.Doesn’t spawn a shell by default to execute the command.Doesn’t spawn a shell.Option to spawn a shellCan be made to create a shell by passing the option shell: trueCan be made to avoid spawning a shell by passing the option shell: falseCan be made to create a shell by passing the option shell: trueDoes not support the shell option.EfficiencySince the default behavior doesn’t involve shell spawning, it is considered to be more efficient than exec.The default behavior is less efficient as a shell needs to be created first before running the given commands.The default behavior is more efficient than the exec method.Doesn’t involve shell spawning, but spawning a large number of child processes might lead to resource-hogging, as the spawned processes will have their own v8 instance.BehaviorAsynchronous AsynchronousAsynchronousAsynchronousGenerated output handling of the executed commandOutput is streamedOutput is bufferedOutput is bufferedOutput is streamedSynchronous VersionspawnSync()execSync()execFileSync()NAConclusion:In general, if one is going to deal with a resource-intensive task that might potentially block the main thread, it will be a good approach from a performance perspective to offload that task to a separate process to make sure that our main thread is not stalled,  thereby preventing our code from blocking the event loop.If your intention of creating a new process is just to scale the number of running instances of your application to serve increased traffic, looking into the `cluster` module will be helpful. If you’d like to explore a multi-threaded approach rather than a multi-processing approach to deal with computationally intensive tasks in Node.js, you should have a look at another module named `worker_threads`.
4002
How Is a Node.JS Child Process Launched?

There is a high probability that you have already ... Read More

How to Become a Successful Full Stack Web Developer?

Full stack developer roles are among the hottest careers in the tech space now. These talented folks can develop a whole product from scratch. A full stack developer is a combination of Front-end developer and Backend developer. These two in themselves are full time jobs and most people make careers out of one of them. So, we will start with Front-end roadmap and then go to Back-end roadmap. A person interested in becoming a Full-stack developer needs to have proficiency in both the front end and back-end tools, just like I started as a Front-end developer and later on become a Full stack developer by mastering JavaScript backend technologies and databases.The demand for Full Stack Web DeveloperThe demand for Full stack developers is the highest in early-stage startups, where they want to create a Minimum Viable Product at the earliest to showcase to the investors. It is also a nice skill to have in addition to frontend technologies or backend technologies alone, since an employer prefers people with both skills.There are a lot of technologies to learn to be a Full-Stack developer. We will discuss about them in the coming sections.   List of technologies to master to become a Full-Stack developer A full-stack developer is actually a combination of Frontend developer and Backend developer. We need to master both, and both have different Roadmaps. Let’s start with the basics. The frontend is the web-site which we see and it is primarily made with HTML and CSS.  JavaScript was also used earlier but nowadays, it is created with JavaScript frameworks like ReactJS, Angular or Vue. All these frameworks require one to learn the basics of HTML, CSS, & JavaScript. So, we need to learn the basics followed by at least one framework.In the backend we have a lot of technologies and databases also. So, we need to choose one backend framework from Java (Spring Framework), JavaScript (NodeJS) etc and then also learn databases. Databases are divided into two categories, which is NoSQL(MongoDB) and SQL(PostgreSQL, MySQL, Oracle) databases. So, you need to choose one of the databases.We are also required to know about DevOps, which is a practice of harmonizing development and operations whereby the entire pipeline from development, testing, deployment, continuous integration and feedback is automated. The knowledge of either AWS or Azure based cloud ecosystem is required, and also CI/CD like Jenkins and containerizing & orchestrating applications using Docker and Kubernetes.1. Frontend RoadmapLearn the BasicsPlease refer to the attached figure for Front-end roadmap, as we will be referring to this throughout this article. We have to start our journey by learning HTML, CSS and JavaScript which is the base for a web-app or website. HTML has changed a bit over the years, with the introduction of HTML 5 and semantics tags, so make sure to update yourself. JavaScript which was released in 1995, didn’t change much during the next 20 years. But once more and more developers started using it, the ECMA committee decided to add some very nice features and enhance the language, and renamed it ES6 in 2015. After that they regularly added new features to the language and have just released ES2020 in June 2020, which has many additional features. So, learn the basic JavaScript first and then upgrade to ES6 and newer versions. CSS is what makes a website or web-app beautiful, and is often considered the hardest part by a developer. Earlier, CSS was very confusing and had a steep learning curve, because of the use of floats to create a layout. Developers usually used to work with CSS frameworks like bootstrap to design a site. But things have changed a lot with the invention of CSS Grid and Flexbox. Some of the best resources to learn the basics are - html.specdeveloper.mozilla.HTMLStyle CSSdeveloper.mozilla.CSSdeveloper.mozilla.JavaScriptGetting Deeper Now, just learning JavaScript and some basic CSS will not make you a good Front-end developer as you have to take a deep dive into JavaScript. We will discuss CSS later, after learning the essentials of JavaScript.JavaScript EssentialsThere are many things associated with JavaScript which we need to learn before moving forward.The Terminal The first thing to learn is to work in a terminal, and master some of the basic commands. If you are on a Mac, it’s already based on Linux and runs most Linux commands. If you are working on Windows then you must install git bash, which will give you a Linux environment to work with. In JavaScript frameworks, we need to run a lot of commands from the terminal, like if we want to install a third-party dependency by npm.  The basics of Linux can be learnt from their official site.1. Linux FoundationVersion ControlNext, learning version control is very important because we should always keep our code in some remote repository like Github. The industry works on Git, which is version control software. It is completely command-based and is used heavily everywhere. Learn the basic commands which will be useful even for an individual developer. Later on, when working with teams, more advanced knowledge of the git command is required.Through the git commands, we store our code in repositories. The most popular ones are Github and Bit Bucket, so we need to learn how to store and link them.The basics of git can be learnt from this awesome tutorial.1. Git TutorialTask Runners   Task runners are applications which are used to automate tasks required in projects. These tasks include minification of JavaScript and CSS files, CSS preprocessing like from SASS to CSS, image optimization and Unit testing. The three popular task runners are npm scripts, gulp and grunt. The npm script is nothing but the package.json file which comes with React projects or is created in a Node.js project using npm init. Gulp and Grunt are much bigger applications and also have a plugin ecosystem that is suited for large JavaScript projects. The basics for these two technologies can be learnt from here. 1. Gulp2. GruntModule Loader and Bundler  Both module loaders and bundlers are required for large JavaScript applications. Knowledge of both is required, if the project you are working is a big Vanilla JavaScript project. When a large JavaScript application consists of hundreds of files, the module loader takes care of the dependency and makes sure all the modules are loaded when the application is executed. Examples are RequireJS and SystemJS.Module bundlers also do the same thing, building it at the time of application build rather than at the runtime. Popular examples are Webpack and Rollup. 1. RequireJS2. Github3. Webpack4. RollupJSTesting  Testing nowadays is very important in any type of project. There are two types of testing; one is known as Unit testing and other as end-to-end testing. For unit testing we write test cases and the most popular tool nowadays is Jest. End-to-end testing is automated testing, which emulates the whole app. Suppose, an app has a login screen and then it shows posts. The testing tool will run the web-app to check whether all the functionalities are done correctly. The two most popular options today are Puppeteer and Cypress. The tutorials to refer for these topics are - 1. Jest2. Puppeteer3. CypressLibraries and FrameworkThey are the most important part of the JavaScript ecosystem nowadays. It all started with the release of AngularJS in 2010. Before that period most enterprise apps were made in Java and were desktop apps. But AngularJS changed everything, because it made it easy to manage big projects with JavaScript and helped to create complex web-apps.1. React   It is the most popular JavaScript library today and is used by both enterprises and startups that have a huge ecosystem. It is not a complete framework like Angular and we have to install third party dependencies for most things. But if you want to learn a framework that will get you a job, then that framework would be ReactJS, and its demand is not going away for the next 5 years. The component approach and its easy learning curve have made React more popular than other frameworks. A good starting tutorial for React is1. ReactJSState Management   In React state management can sometimes become complex, when we need to share data between components. We generally take help of external packages in it with the most popular being Redux. But we also have other state management libraries like XState and Recoil. Server-side rendering   With performance becoming important nowadays, Server-Side Rendering speeds up the React projects even faster. In SSR projects, the React code is rendered on the server and the client browser directly receives the HTML, CSS, JS bundle. The only framework to do it is NextJS. Static Site Generators   Lot of sites don’t need to be updated frequently and it is the place where the only Static Site Generator for ReactJS, which is GatsbyJS shines. With the help of GatsbyJS we can create extremely fast static sites and it gets into Wordpress domain a lot with it. GatsbyJS also has a huge ecosystem of plugins, which enhances its functionalities. React Testing   Unit testing is a very important part of ReactJS projects, especially the ones which are very large. Unit testing ensures that we have lower bugs in Production build. The two popular libraries are – Enzyme and Jest. 2. Angular    It is a complete framework and unlike React requires very few external dependencies. Everything is built within Angular and we don’t have to go outside for more features. Since it was among the earliest frameworks, older projects are in Angular and it is still widely used in enterprises. A good tutorial to learn Angular is below. Angular3. Vue    Vue is another very popular JavaScript library, which has the best features of both ReactJS and Angular and has become very popular in recent years. It is widely used in both enterprise and startups. A good tutorial to start with Vue is below. Vue4. NuxtJS   It is used for Server-Side Rendering in Vue projects and is similar to the NextJS framework used in ReactJS for SSR.  5. Svelte    It is the newest of all frameworks/libraries and has become quite popular, but still not used much in enterprises and startups. It is different from React, Vue and Angular and converts the app at build time rather than at run time as in the other three. Good tutorials to start with Svelte are below. SvelteSvelte handbookCSS Deep DiveA lot has changed in CSS after it included CSS Grid and Flexbox; it has become much easier for developers to work with. CSS Essentials   It is now mandatory for frontend developers to learn CSS Grid and Flexbox, because through it we can develop beautiful layouts with ease. More companies are moving away from CSS Frameworks and have started working with CSS Grid and Flexbox, which are now supported by all browsers. Good tutorials to learn Flexbox and CSS Grid are below. CSS FlexboxCSS GridCSSPreprocessors  CSS preprocessors are used to add special functionalities in CSS, which it lacks. An example is Sass, which adds special features like variables and nested rules in CSS and is widely used in the industry for larger projects. The other popular one is PostCSS, in which we can use custom plugin and tools in CSS. CSS Frameworks  Frameworks were very popular from the early days of CSS, when it was very complicated because of floats. Bootstrap  This is the most popular and oldest CSS framework; easy to learn and also has a wide variety of elements, templates and interfaces. Bulma   It is another CSS framework, which is very popular and much easier to use than bootstrap. Tailwind CSS   This is a fairly new CSS framework and is quite popular nowadays. It follows a different approach than the other frameworks and contains easier classes. Styled Components (React)   This is a CSS in JS library and is for React only. It is used to create components out of every style and is very popular in the React world.  CI/CDThe Continuous Integration/ Continuous deployment is mainly used by DevOps. But a frontend engineer should know its basics. It is used to build, test and deploy applications automatically.Github Actions    It is a freely available CI/CD pipeline, which directly integrates to your github based project and can be used in a variety of languages. Deployment It is again a task which mainly falls into the domain of Backend engineers and DevOps, but a frontend engineer should know some basic and simple tools. Static Deployment   These products are mainly used to deploy static sites, which consists of HTML, CSS and JavaScript only. Two very popular services are Amazon S3 and Surge.sh Node Application Deployment   The projects containing node code cannot be deployed using static deployment. Even if the project is a simple ReactJS project, it also uses node for processing. These applications require services which run the Node code and deploy it. The three most popular services are Vercel, Firebase and Netlify. 2. Backend Roadmap (Including Storage, Services & Deployment)Understanding the BackendBackend is the part of the website that provides the functionality, allowing people to browse their favorite site, purchase a product and log into their account, for instance. All data related to a user or a product or anything else are generally stored in databases or CMS (Content Management System) and when a user visits any website, they are retrieved from there and shown. One of the responsibilities of a backend engineer involves writing APIs, which actually interact with the database and get the data. They are also involved in writing schemas of database and creating the structure of databases. Backend EssentialsFor a backend engineer, working in a Linux environment is an essential skill. A lot of the configurations are done on the terminal. So, he or she should be very good with Linux commands.Also, they should know both commands and the use of any git powered platforms like Github or bitbucket.Languages and FrameworksAll of the popular languages have some framework, which has been used for backend development. These frameworks are generally used to create API endpoints, which are used to fetch or store data in the database. For example, when we scroll articles on Facebook, these articles are fetched from a database and we use the GET method to fetch them. Similarly, when we write an article and hit submit, it uses POST method.Now, different frameworks implement this GET, POST and other APIs also referred to as RESTful APIs in their own way.Java   Java is by far the oldest and the most used language for backend development. It is also used for a variety of other tasks like Android development, but it shines in the backend because of its multithreading abilities. So, enterprise grade web-apps and web-apps with a lot of traffic prefer Java, because it handles loads better. The most popular frameworks for backend development in Java are Spring Framework and Hibernate. Some good beginner's tutorials are - 1. Spring framework2. Hibernate3. JavatpointJavaScript   It is a very popular choice for backend development, because on the frontend side JavaScript is the only choice. So, a lot of frontend engineers can take this choice to become Full-stack developers. Node.js   It allows developers to use JavaScript to write server-side code, through which they can write APIs. Actually, the API part can be done by numerous frameworks of Node.js out of which Express is widely used. The other popular framework is Fastify. Some good beginner's tutorials are - 1. Nodejs2. ExpressJs3. fastifyPython   Python is one of the most popular languages among developers and has been used in a variety of fields. The two most popular frameworks for Python are Flask and Django. Some good beginner tutorials are - 1. Flask2. DjangoC#   It is a very popular programming language which was developed by Microsoft and it has the power of C++. Its popularity increased once the .NET framework was released for backend development. As Microsoft is very popular in enterprises, the .NET framework is generally preferred in enterprises. A good tutorial to learn .NET is - 1. Dotnet2. Dotnet FrameworkGo  Go language which is also referred to as Golang, has gained popularity in recent years. It is used a lot in Backend programming and the two popular frameworks are Gin and Beego. DatabaseFor a Backend engineer, after making APIs with framework based on language, it's time to learn about Databases. Databases are used to store most of the things which we see in a web-app, from user login credentials to user posts and everything else. In the earlier days we only used to have one type of Database and that was Relational databases, which use tables to store data. Now we have two other categories also, one being NoSQL databases and the other In-memory databases. 1. Relational databases   Relational databases allow you to create, update and delete data stored in a table format. This type of database mostly uses SQL language to access the data, hence is also known as an SQL database. MySQL  It is one of the oldest databases and was released in 1995. It is an open-source database and was very popular in the 2000s with the rise of LAMP (Linux, Apache, MySQL, PHP) stack. It is still widely in use, but there are other popular Relational databases. A good tutorial to learn MySQL is - 1. MySQLPostgreSQL  PostgreSQL, which is also known as Postgres is also an old open-source Relational database, which was released in 1996. But it gained popularity recently, as it goes very well with modern stacks containing NodeJS and other backend technologies. A good tutorial to learn PostgreSQL is - 1. PostgreSQLOracle is the most popular and oldest relational database. It was released in 1979 and still remains the number one preference for enterprise customers. All the big banks and other organizations, run on Oracle databases. So, the knowledge of Oracle is a must in many companies for an Engineer. A good tutorial to learn Oracle is - 1. OracleMS-SQL  MS-SQL is also known as Microsoft SQL and is yet another commercial Relational database. It has got different editions, used by different audiences. It is also heavily used by enterprise users and powers a whole lot of big systems around the world. A good tutorial to learn MS-SQL is - 1. SQLServer2. NoSQL databases  NoSQL databases are also called non-SQL databases. The NoSQL databases mainly store data as key-value pairs, but some of them also use a SQL-like structure. These databases have become hugely popular in the 21st century, with the rise of large web-apps which have a lot of concurrent users. These databases can take huge loads, even millions of data connections, required by web-apps like Facebook, Amazon and others. Beside this, it is very easy to horizontally scale  a NoSQL database by adding more clusters, which is a problem in Relational Databases. MongoDB  It is the most popular NoSQL database, used by almost every modern app. It is a free to use database, but the hosting is charged if we host on popular cloud services like MongoDB atlas. Its knowledge is a must for backend engineers, who work on the modern stack. MongoDB uses json like documents to store data. A good tutorial to learn MongoDB is - 1. MongodbIt is a proprietary database service provided by Amazon. It is quite similar to MongoDB and uses key-value pairs to store data. It is also a part of the popular AWS services. A good tutorial to learn DynamoDB is-DynamoDBCassandra is an open-source and free to use NoSQL database . It takes a different approach when compared to other NoSQL databases, because we use commands like SQL, which are known as CQL (Cassandra Query Language). A good tutorial to learn Cassandra is - Cassandra3. In-memory databases   The in-memory database is a database, which keeps all of the data in the RAM. This means it is the fastest among all databases.  The most popular and widely used in-memory database is Redis. Redis  Redis (Remote Dictionary Server) is an in-memory database, which stores data in RAM in a json like key-value format. It keeps the data persistent by updating everything in the transaction log, because when systems are shut down their RAM is wiped clean. A good tutorial to learn Redis - RedisStorageStoring the data is an important part of any application. Although this is mainly DevOps territory, every backend developer should know the basics for the same. We need to store the database data and also the backend code. Beside this the frontend code must also be stored somewhere. Nowadays everything is stored in the cloud, which is preferred by individuals, startups and enterprises. The two most popular cloud-based storages are – Amazon S3 Azure Blob Storage Good beginner's tutorials for both areServices and APIsThese are theoretical concepts and are implemented by various services, but a backend engineer should know them and how to use them. Restful APIs  This is by far the most popular way to get data from a database. It was made more popular, with the rise of web-apps. We do GET, PUT, POST and DELETE operations to read, update, create or delete data from databases. We have earlier discussed different languages and frameworks, which have their own implementations for these operations. Microservices Architecture  In microservice architecture, we divide a large and complex project into small, independent services. Each of these is responsible for a specific task and communicates with other services through simple APIs. Each service is built by a small team from the beginning, and separated by boundaries which make it easier to scale up the development effort if needed. GraphQL  It is the hottest new kid in the block, which is an alternative to the Restful APIs. The problem with Restful APIs is that if you want some data stored in database, you need to get the whole data sent by the endpoint. On the other hand, with GraphQL, you get a query type language which can return only the part of the data which you require.  DevOps & DeploymentA backend engineer requires a fair bit of DevOps knowledge. So, we will next deep dive into the methodologies in DevOps. 1. Containerization & Orchestration   Containers are a method of building, packaging and deploying software. They are similar to but not the same thing as virtual machines (VMs). One of the primary differences is that containers are isolated or abstracted away from the underlying operating system and infrastructure that they run on. In the simplest terms, a container includes both an application’s code and everything that code needs to run properly. Container orchestration is the automatic process of managing the work of individual containers for applications based on microservice architecture. The popular Containerization and Orchestration tools are – Kubernetes Docker Good beginner's tutorials for both are -Kubernetes2. DevOps   DevOps is a set of practices that combine software development (Dev) and IT operations (Ops). It aims to shorten the systems development life cycle and provide continuous delivery with high software quality. The two most popular DevOps services are AWS and Azure. Both of them are cloud based and are market leaders. Both of these platforms contain a wide variety of similar services. AWS  It consists of over 200 products and services for storage, database, analytics, deployment, serverless function and many more. AWS is the market leader as of now with 33% of market share. The AWS certifications are also one of the most in-demand certifications and a must for frontend engineers as well as Backend engineers. Azure  Microsoft Azure is second in terms of market share of cloud-based platforms, with 18% of the market. It also consists of SaaS (Software as a Service), PaaS (Platform as a Service) and IaaS (Infrastructure as a Service) like AWS. 3. PaaS (Platform as a Service)   There are several smaller players, which provide Platform as a Service and are much easier to use than services like AWS and Azure. With these services you can directly deploy your React or other web-apps, by just hosting them on GitHub and pushing the code. These services are preferred a lot by freelancers, hobbyists and small companies as they don’t require investment in learning complicated services like AWS and Azure. The three most popular PaaS services are Digital Ocean Heroku Netlify 4. Serverless  Serverless computing is an execution model where the cloud provider (AWS, Azure, or Google Cloud) is responsible for executing a piece of code by dynamically allocating resources and only charging for the number of resources used to run the code. The code is typically run inside stateless containers that can be triggered by a variety of events including http requests, database events, queuing services, monitoring alerts, file uploads, scheduled events (cron jobs), etc. The code that is sent to the cloud provider for execution is usually in the form of a function. AWS Lambda  It is an event-driven, serverless platform which is part of AWS. The various languages supported by AWS Lambda are Node.js, Python, Java, Go, Ruby and .NET. AWS Lambda was designed for use cases such as updates to DynamoDB tables, responding to a website click etc. After that it will “spin down” the database service, to save resources. Azure Functions  They are quite similar to AWS Lambda, but are for Microsoft Azure. Azure functions have a browser-based interface to write code to respond to events generated by http requests etc. The service accepts programming languages like C#, F#, Node.js, Python, PHP and Java. Serverless Framework  It is an open-source web-framework written using Node.js. The popular services like AWS Lambda, Azure functions and Google cloud functions are based on it. CI/CD A backend developer should know the popular CI/CD (Continuous Integration/Continuous deployment) tools. These tools help to automate the whole process of building, testing and deployment of applications. Github Actions   It is a freely available CI/CD pipeline, which directly integrates to your GitHub based project and can be used in variety of languages. Jenkins  Jenkins is the most popular CI/CD automation tool, which helps in building, testing and deployment of applications. Jenkins was written in Java and over the years has been built to support over 1400 plugins, which extend its functionalities. Circle CI  Circle CI is also a CI/CD automation tool, which is cloud based and so it is different from Jenkins. It is much easier to use than Jenkins, but has a smaller community and lower user base. SecuritySecurity is an important aspect of any application. Most applications containing user personal data, like email etc, are often targeted by hackers. OWASP   The Open Web Application Security Project (or OWASP), is a non-profit organization dedicated to web application security. They have free material available on their website, making it possible for anyone to improve their web application security. Protecting Services & databases against threats   Hackers target databases of popular web-apps on a regular basis to get sensitive information about their customers. This data is then sold to the highest bidder on the dark-net. When such public breaches are reported, then it's a reputation loss for the enterprise also. So, a lot of emphasis should be given to Authentication, Access, Backups, and Encryption while setting up a database. The databases should also be monitored for any suspicious activities. Besides this the API routes also need to be protected, so that the hacker cannot manipulate them. Career roles Most of the companies hire Frontend developers, Backend developers and DevOps engineers separately. This is because most of the enterprise projects are huge, in which roles and responsibilities are distributed. But there is a huge demand for Full Stack developers in the startup sector in US and India. These companies need specialists who can get the product out as soon as possible with agile and small teams. Top companies hiringAlmost every company on the planet is hiring web-developers or outsourcing the development work. Since the past decade, the demand for developers has risen exponentially. The top technology companies which hire full stack developers are Facebook, Amazon, Apple, Netflix, Google, Uber, Flipkart, Microsoft and more.  The sites of each of these companies are web-apps (excluding Apple and Microsoft), with complex frontend and backend systems. The frontend generally consists of React or Angular and the backend is a combination of various technologies. The DevOps part is also quite important in these web-apps as they handle millions of concurrent connections at once.Salaries  The salary of a beginner Frontend developer in India starts from Rs. 300,000($ 3980) per year in service-based companies to Rs. 12,00,000($ 15,971) per year in the top tech companies mentioned above. The salary of a Beginner Full-Stack developer in India starts at Rs. 4,50,000 ($ 5989) per year in service companies to Rs. 12,00,000($ 15,971) per year in top tech companies. The salary for an entry level Frontend developer in USA is $ 59,213 per year and for an entry level Full stack developer is $ 61,042 per year.Below are some sources for salaries. web-developerfull-stack-developerfront-end-vs-back-endTop regions where there is demand There are plenty of remote and freelancing opportunities in web-development across the world. The two countries with most developers and top tech companies are USA and India. Silicon Valley, which is the San Francisco Bay Area, in Northern California, USA is the hub of technology companies.  The top city in India to start a developer job is the Silicon Valley of India – Bengaluru. The number of jobs is more than all the other cities combined and it also has a very good startup ecosystem. Almost all the big technology companies mentioned earlier and top Indian service companies are located in the city. After Bengaluru, the city where the greatest number of technology jobs are based is Hyderabad, followed by Chennai and then Pune. Entry PointsThe demand for web-developers is high and anyone with a passion for creating apps can become a web-developer. An Engineering degree is not mandatory to land a job as a web developer.  The most in-demand skill today and for the next 5 years is React and its ecosystem. So, if you know HTML, CSS, JavaScript and React, it is impossible to not get a job. Career Pathway  Most people start as an intern Front-end developer or Intern Full-Stack developer and in many cases Intern Backend developer. Many companies directly hire junior Frontend/Backend/Full-stack developers.  After that, the next step is the role of Senior Frontend/Backend/Full-stack developers. Many Frontend and Backend developers become full stack developers at this level, by learning additional technologies. Senior resources in Frontend/Backend/Full-stack can then go on to assume Team Lead roles. These people manage small teams in addition to being individual contributors.  After this a professional can become a Project manager, whose main responsibility is managing the team. Another role is that of Technical Project Manager, who manages the team and also has hands-on knowledge in Technology. The last role at this level is that of a Software Architect, who handles and designs big projects and has to look at every aspect of the technology to create the enterprise app. Generally Full-stack developers are preferred in this role, as they need to know all technologies. The highest career milestone is CTO or Chief Technology Officer, who handles all the technology teams and makes all technology decisions in a Technology company. Job SpecializationThere are some Full stack development specializations which I see nowadays in the industry. Full stack developers who work with React in the Frontend and Java in the Backend are in great demand. Similarly, developers who work with Angular in the Frontend and .NET in the backend are in great demand.How KnowledgeHut can helpAll these free resources are a great place to start your Frontend or Full-Stack journey. Beside these there are many other free resources on the internet, but they may not be organized and may not have a structured approach.  This is where KnowledgeHut can make a difference and serve as a one stop shop alternative with its comprehensive Instructor-led live classes. The courses are taught by Industry experts and are perfect for aspirants who wish to become Frontend or FullStack developers.Links for some of the popular courses & Bootcamps by KnowledgeHut are appended below-CSS3JavaScriptReactJSNodeJSDevopsFull-stack developer BootcampFront-end developer Bootcampback-end developer BootcampConclusion This completes our article on the Full stack developer journey by combining both the Frontend and backend roadmap. There are many people who become backend developers first by working on languages like Java and then go on to learn React to become full stack developers.  Again, many developers learn front-end development first with frameworks like React, and then become full stack developers by learning Node.JS. This path is easier for developers because both React and Node.JS use the same language which is JavaScript.We hope you have found this blog useful, and can now take the right path to become a full stack developer. Good luck on your learning journey!
9730
How to Become a Successful Full Stack Web Develope...

Full stack developer roles are among the hottest c... Read More