Search

What Is React-js State?

You must have already learned about the basic building block of any React application which is a Component.  A component represents a feature that may be made up of several smaller components. Components can be broadly classified into functional or class components.  Components may take in some values as properties (prop) to render a page. These props decide how to render a page. function Welcome(props) {   return < h1 >Hello, {props.name}</h1>; }In addition to props, a component can also have a state that holds a value that can keep a track of all the information within a component. In this article, we will focus mainly on what is State, how we can define and utilize State and how components can use it in data management.  Defining React StateSo what exactly is state? What is it used for?    State represents a component’s underlying data model and is rendered by the component. But more importantly, whenever data in the state changes, it causes the component to re-render to reflect the change. This facilitates declarative programming where you can simply manipulate state; while React takes care of implementing updates to ensure your component reflects the data in the State accurately.  In Class component we can use State as follows:  class Welcome extends React.Component {     constructor() {         super();         // Space To define the state         this.state = {            isDisabled: false,            totalCost: 0,            products: []         }     }     // To Define render method  } We can also use state in Functional components using the useState Hook. Hooks are a new addition in React 16.8 which let us use State and other React features in functional components.  When should I use a Hook?If you are writing a functional component and realize that you need to add a State to it, the only option previously was to convert it to a class. Now you can use a Hook inside the existing function component.  For this, you can directly read the React documentation of Hooks here. In this article, we will mainly focus on “what is a State” and how is it different from Props. Difference of Props and State Most of the developers who are new to React often think about when to use State and when to use a Prop. Let’s understand this dilemma with an example.   A React component is akin to a JavaScript function.  A State can only be utilized in class components natively and is quite similar to a Prop, with the only exception that it is fully private, which means it can only be fully controlled and accessed by a component. In functional components, you have to opt-in to the useState hook to include stateful features.  Props, on the other hand, allow you to reuse the component by giving it an ability to receive data as input from the parent component.   We will learn more about the State and its usage later in this article, but here is the practical difference between the two:  A fictional example of Using a State: class MyComponent extends React.Component {     state = {         name: 'Tom'  //defining the name property inside component state     }     render() {         return <div>Hello {this.state.name}</div>;     }  }  Here, we can use the state ‘name’ anywhere in the component named “MyComponent” with the value ‘Tom’, or we can assign a new state also in the same component. And, Using a Prop:A Prop is a short name for properties. React is nothing without a Prop. Earlier we saw an example where we used the same data over and over again, but what if we have a scenario where we need the same component but not the same data? For example, I might want the theme component, but instead of a dark theme, I would like to use a light theme! What I mean here is that basically, I want to re-use “MyComponent” again, but not the data defined in it. This is where Props will come in useful; in cases when we want to change the content inside the reusable component.     class ThemeProvider extends React.Component {     render() {         return <div>Current theme is {this.props.theme}</div>;     }    }  // when re-using the component with differnt data  <ThemeProvider name="Light" />  <ThemeProvider name="Dark" />            It’s absolutely fine if you are not familiar with this code snippet. The idea is to understand when to use state or prop, and not the code as of now!  For now, just know that Prop is just a state, which is passed from parent to child. And because props can’t change their value in the child component, they take the help of an event listener or callback function in the parent component.    Now let’s quickly jump into the basics of a State.    Creating the State Object  React component has a built-in state object. Before you think that state is a very simple concept, let me stop you right there!  It’s not!  You should not forget the data flow in React! In React there is a uni-direction flow of data, which is from parent to child. This can be a bit confusing, in that different components will never know what is changing in their component and when. Besides, they might be unaware of whether a component is stateless or stateful.   This is why the state is usually said to be encapsulated or having a local scope.This is why the state is usually said to be encapsulated or having a local scope. And therefore, you initialize the state in the class component by simply using a constructor.    Inside the Constructor  To declare a local state in the component, we can use a constructor as follows:   class Welcome extends React.Component {     constructor() {         super();         this.state = {             name: 'Michael Jackson',             currentTimer: 0,             hasPicked: false,             themeRed: false,             todoList: []         }     }     render() {         return <p>My name is {this.state.name}</p>;     }  }    And the output or the result of the above < p> tag will be rendered as:     Hello, my name is Michael Jackson However, this was the older convention of declaring a state. We can also declare a state without the ‘constructor’ and ‘super’ keywords with the help of Property Initializer which came in 2017.    Wait, what is Property Initializer?     If you have a lot of code, it becomes harder to understand what is what. And if there are any arguments in the constructor, then it becomes an extra overhead to keep track of all of them.      Therefore, the idea behind using an Initializer is to use a cleaner ES6 component, by assigning an arrow function to a property that will act like a normal method. In other words, it can also be termed as class field syntax.         Without the Constructor       Take a look at the representation below:         class Welcome extends React.Component {  state = {       name: 'Michael Jackson'     }  }  render() {    …  }  }  In the following example, we have added a state to the “Welcome” component.         Let’s see how we can consume the data from the object — not outside the component, but within it!           Rendering data from state                 A state is either initialized in the constructor or by using the class fields syntax to directly initialize it in a class component. Now let’s see how we can consume the state from the component in the render.           A point to note here while using state is we use “this.state” to get the value of the name property and it can be accessed in the render() method as follows:             ~~~Wrong Approach~~~  class Welcome extends React.Component {     constructor() {         super();         this.state = {             name: 'Michael Jackson'         }     }     render() {         const { name } = this.state         return < h1 >My name is {name}</h1>;     }  } or an alternative to the above is:  ~~~Right Approach~~~ class Welcome extends React.Component {  constructor() {     super();     this.state = {       name: 'Michael Jackson'     }  }  render() {    return < h1 >My name is { this.state.name }</h1>;  }  } The only difference in both is that in the first snippet I used State as:  const { name } = this.state  But we have already initialized the state in the constructor, why should we do it again?  We should not reassign it, and hence we should never update the component state directly.  A state should always be accessed using this.state.propertyName.  Updating the State So far, we have seen how to create state and use state in the component.      Now let’s understand why and how to update state and what happens after updating a state.           A state can’t be changed directly and the only permissible way of updating it is by using setState as follows:             this.state.site = "Welcome"; // wrong implementation    this.setState({ // correct implementation     site: "Welcome"  });    // Or  this.setState((prevState, props) => ({ site: "Welcome" })))  The setState( ) method makes the component re-render; and hence when a state changes the component re-renders and updates the changes.   Each time setState is called, it sends a request to React to update and re-render and give it back a newly updated state.   Let’s understand this with an example:  Let’s suppose we have a component and want to change the name in the component with a method called handleNameChange(). It should look as follows:          handleNameChange(name) {     this.setState({ name })  }   The above method receives an argument and it uses that argument to update the state.              Component Demo to update a state should look as follows:             class App extends React.Component {     constructor() {         super()         this.state = { name: 'Michael Jackson' }     }     handleNameChange(name) {         this.setState({ name })     }     render() {         const { name } = this.state         return (             <div>                 < div>                     < input                         type="text"                         value={this.state.name}                         onChange={event => this.handleNameChange(event.target.value)}                     />                 </ div>                 <p>My name is, {name}</p>             </ div>         )     }  }  When is setState asynchronous?React doesn’t have just one job to do, or only one component to observe for. It is possible that different components will be asking for different updates and DOM manipulations at the same time, hence the state updates are merged!      When setState() is called, React merges the object provided into the current state object.            For example, if we have different variables in our state like this:           constructor(props) {     super(props);     this.state = {         likes: [],         names: []     };  }  And both states can be independently updated by using setState() calls as follow:componentDidMount() {     fetchLikes().then(response => {         this.setState({             likes: response.likes         });     });       fetchNames().then(response => {         this.setState({             names: response.names         });     });  }  Here we are calling multiple setState during one update cycle, so this.setState({names}) will leave this.state.likes unmarked but will completely replace this.state.names.  Hence you will not get the recently updated data in {names} and previous changes will be lost.  A quick fix to the above problem is as follows: Instead of giving a new state directly we can provide a function that can automatically provide the current state into a new state. There are two approaches to this:  // Method #1  this.setState({ foo: this.state.counter + 1 }, this.anyCallback);  Or              // Method #2  this.setState((prevState) => { return { counter: prevState.counterfoo + 1 } }, this.anyCallback);  The main difference is that in example #1, the counter gets incremented by 1 based on the state at the time when you have called the setState() method, whereas In the example-2, the counter will be incremented by 1 only depending on the value that the previous state had while the arrow function was called.  So if we have multiple setState() which happen at the same time before the actual state update, it is possible that they may conflict or have outdated state data, but if we go with approach #2 they are guaranteed to have the most recent updated state because they update synchronously! To learn more about setState() and its powers, head over to this official link.Bonus Section:  Changing Title on Click Example Using StateSo far you have understood how to use State in React and what are the basic principles that define when to use State and when to use Prop. Here is a simple Demo for using State in a component and using Props to reuse the component.    Try this code to understand the power of State and reusable components.         let imgLogo = 'https://apod.nasa.gov/apod/image/2009/CrabNebula_Hubble_960.jpg';    class BonusExample extends React.Component {      constructor() {          super();          this.state = {              newTitle: false          };          this.changeTitle = this.changeTitle.bind(this);      }      changeTitle() {          this.setState({              newTitle: !this.state.newTitle          });      }      render() {          let title = this.state.newTitle ? 'Here is my New Title - Google Page' : 'Here is my Old Title - Facebook Page';          let link;          if (this.state.newTitle) {              link = <NewPageLink />;          } else {              link = <OldPageLink />;          }          return (              < div>                  <Header ><LogoComponent /></Header>                  <Main title={title}>                      {link}                      <div className=" wrapper">                          < button style={{ margin: '20px' }} type="button" className="btn btn-primary" onClick={this.changeTitle}>Change Name</button>                      </div>                  </Main>                  <Footer>< HelperComponent /></Footer>              </div>          );      }  }    class OldPageLink extends React.Component {      render() {          return (              <div style={{margin:'20px'}} className="wrapper">                  <a target="_blank" href= "http://www.facebook.com" > http: //www.facebook.com</a>              </div>          );      }  }    class NewPageLink extends React.Component {      render() {          return (              <div style={{ margin: '20px' }} className="wrapper">                  <a target="_blank" href= "http://www.google.com" > http: //www.google.com</a>              </div>          );      }  }    class Header extends React.Component {      render() {          return (              <header>                  {this.props.children}              </header>          );      }  }    class Main extends React.Component {      render() {          return (              <div>                  <h 1>{this.props.title}</h1>                  {this.props.children}              </div>          );      }  }    class Footer extends React.Component {      render() {          return (              <footer>                  {this.props.children}              </footer>          );      }  }    class LogoComponent extends React.Component {      render() {          return (              <img width="150px" src={imgLogo} />          );      }  }    class HelperComponent extends React.Component {      render() {          return (              <p>Changing the title from one to Another</p>          );      }  }    ReactDOM.render(<BonusExample />, document.getElementById('example'));  ConclusionI hope you have understood the concept of State and its usage. We have learned the basic difference between State and Props and when each should be used. We have also understood the data flow in a React component and how to consume and update a State object in React.  Now that you have understood all the fundamentals of State, there are some high-level pointers that you should always keep in mind while using a State. State is private to a component State Updates have shallow merging You should never modify a State Directly Updates in a State may Be asynchronous State is only used when you want to change component dataWe hope you have found this article useful. Happy Learning!   

What Is React-js State?

10K
What Is React-js State?

You must have already learned about the basic building block of any React application which is a Component 

A component represents a feature that may be made up of several smaller components. Components can be broadly classified into functional or class components.  

Components may take in some values as properties (prop) to render a page. These props decide how to render a page. 

function Welcome(props) { 
  return < h1 >Hello, {props.name}</h1>; 
}

In addition to props, a component can also have a state that holds a value that can keep a track of all the information within a component. 

In this article, we will focus mainly on what is State, how we can define and utilize State and how components can use it in data management.  

Defining React State

So what exactly is state? What is it used for?    

State represents a component’s underlying data model and is rendered by the component. But more importantly, whenever data in the state changes, it causes the component to re-render to reflect the change. This facilitates declarative programming where you can simply manipulate state; while React takes care of implementing updates to ensure your component reflects the data in the State accurately.  

In Class component we can use State as follows:  

class Welcome extends React.Component { 
   constructor() { 
       super(); 
       // Space To define the state 
       this.state = { 
          isDisabled: false, 
          totalCost: 0, 
          products: [] 
       } 
   } 
   // To Define render method 
} 

We can also use state in Functional components using the useState Hook. Hooks are a new addition in React 16.8 which let us use State and other React features in functional components.  

When should I use a Hook?

If you are writing a functional component and realize that you need to add State to it, the only option previously was to convert it to a class. Now you can use a Hook inside the existing function component.  

For this, you can directly read the React documentation of Hooks here. 

In this article, we will mainly focus on “what is a State” and how is it different from Props. 

Difference of Props and State 

Most of the developers who are new to React often think about when to use State and when to use a Prop. Let’s understand this dilemma with an example.   

A React component is akin to a JavaScript function.  A State can only be utilized in class components natively and is quite similar to a Prop, with the only exception that it is fully private, which means it can only be fully controlled and accessed by a component. In functional components, you have to opt-in to the useState hook to include stateful features.  

Props, on the other hand, allow you to reuse the component by giving it an ability to receive data as input from the parent component.   

We will learn more about the State and its usage later in this article, but here is the practical difference between the two:  

A fictional example of Using a State: 

class MyComponent extends React.Component { 
   state = { 
       name: 'Tom'  //defining the name property inside component state 
   } 
   render() { 
       return <div>Hello {this.state.name}</div>; 
   } 
}  

Here, we can use the state ‘name’ anywhere in the component named “MyComponent” with the value ‘Tom’, or we can assign a new state also in the same component. 

And, Using Prop:

Prop is a short name for properties. React is nothing without a Prop. Earlier we saw an example where we used the same data over and over again, but what if we have a scenario where we need the same component but not the same data? For example, I might want the theme component, but instead of a dark theme, I would like to use a light theme! 

What I mean here is that basically, I want to re-use “MyComponent” again, but not the data defined in it. This is where Props will come in useful; in cases when we want to change the content inside the reusable component.     

class ThemeProvider extends React.Component { 
   render() { 
       return <div>Current theme is {this.props.theme}</div>; 
   } 
 
} 
// when re-using the component with differnt data 
<ThemeProvider name="Light" /> 
<ThemeProvider name="Dark" />         

  What Is React-js State? It’s absolutely fine if you are not familiar with this code snippet. The idea is to understand when to use state or prop, and not the code as of now!  

For now, just know that Prop is just a state, which is passed from parent to child. And because props can’t change their value in the child component, they take the help of an event listener or callback function in the parent component.    

Now let’s quickly jump into the basics of a State.    

Creating the State Object  

React component has a built-in state object. 

Before you think that state is a very simple concept, let me stop you right there!  

It’s not!  

You should not forget the data flow in React! In React there is a uni-direction flow of data, which is from parent to child. This can be a bit confusing, in that different components will never know what is changing in their component and when. Besides, they might be unaware of whether a component is stateless or stateful.   

This is why the state is usually said to be encapsulated or having a local scope.

This is why the state is usually said to be encapsulated or having a local scope. 

And therefore, you initialize the state in the class component by simply using a constructor.    

Inside the Constructor  

To declare a local state in the component, we can use a constructor as follows:   

class Welcome extends React.Component { 
   constructor() { 
       super(); 
       this.state = { 
           name: 'Michael Jackson', 
           currentTimer0, 
           hasPickedfalse, 
           themeRedfalse, 
           todoList: [] 
       } 
   } 
   render() { 
       return <p>My name is {this.state.name}</p>; 
   } 
}    

And the output or the result of the above < p> tag will be rendered as:     

Hello, my name is Michael Jackson 

However, this was the older convention of declaring a state. We can also declare a state without the ‘constructor’ and ‘super’ keywords with the help of Property Initializer which came in 2017.    

Wait, what is Property Initializer?     

If you have a lot of code, it becomes harder to understand what is what. And if there are any arguments in the constructor, then it becomes an extra overhead to keep track of all of them.      

Therefore, the idea behind using an Initializer is to use a cleaner ES6 component, by assigning an arrow function to a property that will act like a normal method. In other words, it can also be termed as class field syntax.         

Without the Constructor       

Take a look at the representation below:         

class Welcome extends React.Component { 
state = { 
     name: 'Michael Jackson' 
   } 
} 
render() { 
  … 
} 
}  

In the following example, we have added a state to the “Welcome” component.         

Let’s see how we can consume the data from the object  not outside the component, but within it!           

Rendering data from state                 

A state is either initialized in the constructor or by using the class fields syntax to directly initialize it in a class component. Now let’s see how we can consume the state from the component in the render.           

A point to note here while using state is we use “this.state” to get the value of the name property and it can be accessed in the render() method as follows:             

~~~Wrong Approach~~~ 
class Welcome extends React.Component { 
   constructor() { 
       super(); 
       this.state = { 
           name: 'Michael Jackson' 
       } 
   } 
   render() { 
       const { name } = this.state 
       return < h1 >My name is {name}</h1>; 
   } 
} 

or an alternative to the above is:  

~~~Right Approach~~~
class Welcome extends React.Component { 
constructor() { 
   super(); 
   this.state = { 
     name: 'Michael Jackson' 
   } 
} 
render() { 
  return < h1 >My name is { this.state.name }</h1>; 
} 
} 

The only difference in both is that in the first snippet I used State as:  

const { name } = this.state 

 But we have already initialized the state in the constructor, why should we do it again?  

We should not reassign it, and hence we should never update the component state directly.  

A state should always be accessed using this.state.propertyName.  

Updating the State 

So far, we have seen how to create state and use state in the component.      

Now let’s understand why and how to update state and what happens after updating a state.           

A state can’t be changed directly and the only permissible way of updating it is by using setState as follows:             

this.state.site = "Welcome"// wrong implementation 
 
this.setState({ // correct implementation 
   site: "Welcome" 
}); 
 
// Or 
this.setState((prevState, props) => ({ site: "Welcome" })))  

The setState( ) method makes the component re-render; and hence when a state changes the component re-renders and updates the changes.   

Each time setState is called, it sends a request to React to update and re-render and give it back a newly updated state.   

Let’s understand this with an example:  

Let’s suppose we have a component and want to change the name in the component with a method called handleNameChange(). It should look as follows:          

handleNameChange(name) { 
   this.setState({ name }) 
}  

 The above method receives an argument and it uses that argument to update the state.              

Component Demo to update a state should look as follows:             

class App extends React.Component { 
   constructor() { 
       super() 
       this.state = { name: 'Michael Jackson' } 
   } 
   handleNameChange(name) { 
       this.setState({ name }) 
   } 
   render() { 
       const { name } = this.state 
       return ( 
           <div> 
               < div> 
                   < input 
                       type="text" 
                       value={this.state.name} 
                       onChange={event => this.handleNameChange(event.target.value)} 
                   /> 
               </ div> 
               <p>My name is, {name}</p> 
           </ div> 
       ) 
   } 
}  

When is setState asynchronous?

React doesn’t have just one job to do, or only one component to observe for. It is possible that different components will be asking for different updates and DOM manipulations at the same time, hence the state updates are merged!     

When setState() is called, React merges the object provided into the current state object.            

For example, if we have different variables in our state like this:           

constructor(props) { 
   super(props); 
   this.state = { 
       likes: [], 
       names: [] 
   }; 
}  

And both states can be independently updated by using setState() calls as follow:

componentDidMount() { 
   fetchLikes().then(response => { 
       this.setState({ 
           likes: response.likes 
       }); 
   }); 
 
   fetchNames().then(response => { 
       this.setState({ 
           names: response.names 
       }); 
   }); 
}  

Here we are calling multiple setState during one update cycle, so this.setState({names}) will leave this.state.likes unmarked but will completely replace this.state.names.  

Hence you will not get the recently updated data in {names} and previous changes will be lost.  

A quick fix to the above problem is as follows: Instead of giving a new state directly we can provide a function that can automatically provide the current state into a new state. There are two approaches to this:  

// Method #1 
this.setState({ foothis.state.counter + 1 }, this.anyCallback);  

Or              

// Method #2 
this.setState((prevState) => return { counter: prevState.counterfoo + 1 } }, this.anyCallback);  

The main difference is that in example #1, the counter gets incremented by 1 based on the state at the time when you have called the setState() method, whereas 

In the example-2, the counter will be incremented by 1 only depending on the value that the previous state had while the arrow function was called.  

So if we have multiple setState() which happen at the same time before the actual state update, it is possible that they may conflict or have outdated state data, but if we go with approach #2 they are guaranteed to have the most recent updated state because they update synchronously! 

To learn more about setState() and its powers, head over to this official link.

Bonus Section:  

Changing Title on Click Example Using State

So far you have understood how to use State in React and what are the basic principles that define when to use State and when to use Prop. Here is a simple Demo for using State in a component and using Props to reuse the component.   

 Try this code to understand the power of State and reusable components.         

let imgLogo = 'https://apod.nasa.gov/apod/image/2009/CrabNebula_Hubble_960.jpg'; 
 
class BonusExample extends React.Component { 
    constructor() { 
        super(); 
        this.state = { 
            newTitlefalse 
        }; 
        this.changeTitle = this.changeTitle.bind(this); 
    } 
    changeTitle() { 
        this.setState({ 
            newTitle: !this.state.newTitle 
        }); 
    } 
    render() { 
        let title = this.state.newTitle ? 'Here is my New Title - Google Page' : 'Here is my Old Title - Facebook Page'; 
        let link; 
        if (this.state.newTitle) { 
            link = <NewPageLink />; 
        } else { 
            link = <OldPageLink />; 
        } 
        return ( 
            < div> 
                <Header ><LogoComponent /></Header> 
                <Main title={title}> 
                    {link} 
                    <div className=" wrapper"> 
                        < button style={{ margin: '20px' }} type="button" className="btn btn-primary" onClick={this.changeTitle}>Change Name</button> 
                    </div> 
                </Main> 
                <Footer>< HelperComponent /></Footer> 
            </div> 
        ); 
    } 
} 
 
class OldPageLink extends React.Component { 
    render() { 
        return ( 
            <div style={{margin:'20px'}} className="wrapper"> 
                <a target="_blank" href"http://www.facebook.com" > http: //www.facebook.com</a> 
            </div> 
        ); 
    } 
} 
 
class NewPageLink extends React.Component { 
    render() { 
        return ( 
            <div style={{ margin: '20px' }} className="wrapper"> 
                <a target="_blank" href= "http://www.google.com" > http: //www.google.com</a> 
            </div> 
        ); 
    } 
} 
 
class Header extends React.Component { 
    render() { 
        return ( 
            <header> 
                {this.props.children} 
            </header> 
        ); 
    } 
} 
 
class Main extends React.Component { 
    render() { 
        return ( 
            <div> 
                <h 1>{this.props.title}</h1> 
                {this.props.children} 
            </div> 
        ); 
    } 
} 
 
class Footer extends React.Component { 
    render() { 
        return ( 
            <footer> 
                {this.props.children} 
            </footer> 
        ); 
    } 
} 
 
class LogoComponent extends React.Component { 
    render() { 
        return ( 
            <img width="150px" src={imgLogo} /> 
        ); 
    } 
} 
 
class HelperComponent extends React.Component { 
    render() { 
        return ( 
            <p>Changing the title from one to Another</p> 
        ); 
    } 
} 
 
ReactDOM.render(<BonusExample />, document.getElementById('example'));  

Conclusion

I hope you have understood the concept of State and its usage. We have learned the basic difference between State and Props and when each should be used. We have also understood the data flow in a React component and how to consume and update a State object in React.  

Now that you have understood all the fundamentals of State, there are some high-level pointers that you should always keep in mind while using a State. 

  • State is private to a component 
  • State Updates have shallow merging 
  • You should never modify a State Directly 
  • Updates in a State may Be asynchronous 
  • State is only used when you want to change component data

We hope you have found this article useful. Happy Learning!   

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 *

SPECIAL OFFER Upto 20% off on all courses
Enrol Now

Trending blog posts

Suggested Blogs

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. 
9272
What are React Component Lifecycle Methods

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

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 (                  Hello world!              );    }  } 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.      Header {this.state.content}      Enter your username:          Enter your password:            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.
5819
What are the Pros and Cons of React

If you are a web developer, you are a JavaScript... Read More