React component lifecycle

React component lifecycle is a serial of methods that are automatically called by react at certain points during. This method are an optional methods. We can optionally define inside our class-based components. Let’s dive in the react component lifecycle tutorial

Basically all the React component lifecycle methods has split in four phases: initialization, mounting, updating and unmounting. Let’s take a closer look at each one of them.

The following image is the visual representation of the phases and the methods of ReactJs lifecycle.


Initialization

This is the first stage in the ReactJS lifecycle. In this phase the developer has to define the props (properties) and initial state of the component this is generally done in the constructor of the component. The following example describes the initialization process

constructor(props) { 
   super(props); 
   this.state = { hello : "World!" }; 
}

Mounting

Mounting means putting elements into the DOM.

Mounting is the phase of the component lifecycle when the initialization of the component is completed and the component is mounted on the DOM and rendered for the first time in the webpage. Mounting phase consists of two such predefined functions as described below.

  • componentWillMount() Function: As the name clearly suggests, this function is invoked right before the component is mounted on the DOM i.e. this function gets invoked once before the render() function is executed for the first time.
  • componentDidMount() Function: This method runs after the component output has been rendered to the DOM i.e. this function gets invoked once after the render() function is executed for the first time.

Updation

Updation is the phase where the states and props of a component are updated followed by some user events such as clicking, pressing a key on keyboard etc. The following are the descriptions of functions that are invoked at different points of Updation phase.

componentWillRecieveProps() Function: This is a Props exclusive Function and is independent of States. This function is invoked before a mounted component gets its props reassigned. The function is passed the new set of Props which may or may not be identical to the original Props. Thus checking is a mandatory step in this regards. The following code snippet shows a sample use-case.

componentWillRecieveProps(newProps) 
{ 
    if (this.props !== newProps) { 
        console.log(" New Props have been assigned "); 
        // Use this.setState() to rerender the page. 
    } 
}
  • setState() Function: This is not particularly a Lifecycle function and can be invoked explicitly at any instant. This function is used to update the State of a component. You may refer to this article for detailed information.
  • shouldComponentUpdate() Function: By default, every state or props update re-render the page but this may not always be the desired outcome, sometimes it is desired that on updating the page will not be repainted. The shouldComponentUpdate() Function fulfills the requirement by letting React know whether the component’s output will be affected by the update or not.

    shouldComponentUpdate() is invoked before rendering an already mounted component when new props or state are being received. If returned false then the subsequent steps of rendering will not be carried out. This function can’t be used in case of forceUpdate(). The Function takes the new Props and new State as the arguments and returns whether to re-render or not.
  • componentWillUpdate() Function: As the name clearly suggests, this function is invoked before the component is rerendered i.e. this function gets invoked once before the render() function is executed after the updation of State or Props.
  • componentDidUpdate() Function: Similarly this function is invoked after the component is rerendered i.e. this function gets invoked once after the render() function is executed after the updation of State or Props.

Unmounting

This is the final phase of the lifecycle of the component that is the phase of unmounting the component from the DOM. The following function is the sole member of this phase.

  • componentWillUnmount() Function: This function is invoked before the component is finally unmounted from the DOM i.e. this function gets invoked once before the component is removed from the page and this denotes the end of the lifecycle.

We have so far discussed every predefined function there was in the lifecycle of the component and we have also specified the order of execution of the function. Let us now see one final example to finish of the article while revising what’s discussed above.

Creating new component

Create new component and put the below code on it and import in the index.js file

import React from 'react'; 
import ReactDOM from 'react-dom'; 
  
class ComponentLifecycle extends React.Component { 
    
    constructor(props) { 
        super(props); 
        this.state = { hello : "World!" }; 
    } 
  
    componentWillMount() { 
        console.log("componentWillMount()"); 
    } 
  
    componentDidMount() { 
        console.log("componentDidMount()"); 
    } 
  
    changeState() { 
        this.setState({ hello : "W3path!" }); 
    } 
    
    shouldComponentUpdate(nextProps, nextState) { 
        console.log("shouldComponentUpdate()"); 
        return true; 
    } 
  
    componentWillUpdate() { 
        console.log("componentWillUpdate()"); 
    } 
  
    componentDidUpdate() { 
        console.log("componentDidUpdate()"); 
    } 

    componentWillUnmount() {
        console.log('componentWillUnmount()');
    }

    render() 
    { 
        return ( 
            <div className="mt-5"> 
                <h2>Hello { this.state.hello }</h2> 
                <button className="btn btn-primary mt-2" onClick={this.changeState.bind(this)}>Press Here!</button>
            </div>
        ); 
    }
}

export default ComponentLifecycle;

Running the App

Run application using npm start.

10 Comments

  1. generic propecia said:

    Thank you for every one of your hard work on this web page. My daughter really loves making time for investigations and it’s really obvious why. Most people learn all of the lively mode you offer priceless tactics through this web site and even inspire participation from some other people on the matter so our favorite girl is now starting to learn a lot of things. Take advantage of the rest of the year. You are always doing a remarkable job. https://harrington-service.com/

    January 8, 2021
    Reply
  2. aripiprazole generic said:

    I simply wanted to thank you so much once more. I am not sure the things that I would’ve made to happen without the type of solutions revealed by you over that situation. It truly was an absolute hard matter in my opinion, however , seeing the very specialised strategy you resolved that made me to leap over gladness. I am just happy for this information and then pray you realize what a great job you happen to be providing teaching people today thru your web site. More than likely you have never got to know any of us. https://abilifyaripiprazoles.com/

    January 8, 2021
    Reply
  3. venlor without a prescription said:

    I enjoy you because of all of the effort on this blog. Betty delights in carrying out internet research and it’s easy to see why. A lot of people hear all about the compelling form you convey advantageous guidance by means of the blog and attract contribution from other individuals about this area and my child has always been becoming educated a great deal. Enjoy the remaining portion of the new year. You’re carrying out a brilliant job. https://venlorz.com/#

    January 9, 2021
    Reply
  4. Cherie said:

    naturally like your website but you have to take a look at the spelling on quite a few of your posts.
    A number of them are rife with spelling issues and I
    find it very troublesome to inform the truth
    on the other hand I will surely come back again.

    my blog: cheap flights

    January 31, 2021
    Reply
  5. Jung said:

    Woah! I’m really loving the template/theme of this blog. It’s simple, yet effective.
    A lot of times it’s very difficult to get that “perfect balance” between superb usability and
    visual appeal. I must say you’ve done a superb job with this.
    In addition, the blog loads extremely quick for me on Safari.
    Superb Blog!

    Here is my website; cheap flights

    February 1, 2021
    Reply
  6. Darrel said:

    Howdy! This post couldn’t be written any better! Reading through this post
    reminds me of my old room mate! He always kept chatting about this.

    I will forward this write-up to him. Pretty sure he will have
    a good read. Thanks for sharing!

    my site – cheap flights

    February 1, 2021
    Reply
  7. Penney said:

    Why viewers still make use of to read news papers when in this technological globe all is
    existing on net?

    Visit my site cheap flights (http://tinyurl.com/y4477sms)

    February 2, 2021
    Reply
  8. Karen said:

    I really love your site.. Great colors & theme. Did you make this web site yourself?
    Please reply back as I’m trying to create my own personal blog and would
    like to know where you got this from or what the theme is named.
    Thank you!

    Feel free to surf to my blog – cheap flights

    February 2, 2021
    Reply
  9. Muoi said:

    I used to be suggested this web site through my cousin. I’m no longer positive whether or not this post is
    written by him as nobody else know such unique approximately my trouble.
    You are amazing! Thank you!

    Here is my page: cheap flights (tinyurl.com)

    February 3, 2021
    Reply
  10. Wilma said:

    It’s actually a great and helpful piece of information. I’m glad that
    you simply shared this helpful info with us.
    Please keep us up to date like this. Thank you for sharing.

    Review my web site: cheap flights (tinyurl.com)

    February 12, 2021
    Reply

Leave a Reply

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