More

    React Lifecycle: Everything You Need to Know About It

    What are React Lifecycle Methods?

    The React Lifecycle methods can be thought of as the series of events that occur from the birth of a React component to its death. 

     Every component in React goes through a lifecycle of events. These events can be thought of as them going through a cycle of birth, growth and death. 

     

    Stages in the React Lifecycle- 

    1)    Mounting- Birth of the component

    2)    Update- Growth of the component

    3)    Unmount- Death of the component. 

     

    Each of the components in react can be monitored and manipulated during the above mentioned three stages in the lifecycle.

     

    Mounting-

     Mounting means putting elements into the DOM. 

     In react, four built-in methods are called in order when mounting a component. 

     These four methods are: 

    1)    Constructor()

    2)    getDerivedStateFromProps()

    3)    render()

    4)    componentDidMount()

     

    The render() method is required and will always be called, the others are only optional and will only be called if you define them. 

     

    Constructor

    The constructor() method is the first method that we call when the component is initiated and it acts as the natural place to set up the initial state and other initial values. 

     The constructor() method is called with the props, as arguments, and it is important to remember that you should always start by calling the super(props) before anything else, this will initiate the parent constructor method and allow the components to inherit methods from its parent, React.Component. 

     For Example: This is the constructor method called by react, every time you make a component: 

     

    class Header extends React.Component {

      constructor(props) {

        super(props);

        this.state = {favoritecolor: “red”};

      }

      render() {

        return (

          <h1>My Favorite Color is {this.state.favoritecolor}</h1>

        );

      }

    }

     

    ReactDOM.render(<Header />, document.getElementById(‘root’));

     

    getDerivedStateFromProps:

     

    the getDerivedStateFromProps() method is called right before we render the elements present in the DOM. 

     

    This is the natural place to set the state object on the basis of the initial props. 

     

    It takes state as an argument and returns an object with changes made to its state. 

     

    The example below starts with the favourite color being “red”, but the getDerivedStateFromProps() method updates the favorite color based on the favcol attribute. 

     

    For example: 

    The getDerivedStateFromProps method is called to use right before the render method.

     

    class Header extends React.Component {

      constructor(props) {

    super(props);

    this.state = {favoritecolor: “red”};

      }

      static getDerivedStateFromProps(props, state) {

    return {favoritecolor: props.favcol };

      }

      render() {

    return (

       <h1>My Favorite Color is {this.state.favoritecolor}</h1>

    );

      }

    }

     

    ReactDOM.render(<Header favcol=”yellow“/>, document.getElementById(‘root’));

     

    Render: 

     It is the method that is necessary, without which the program will not run. This is also the method that actually outputs the HTML to the DOM. 

     

    An example is: 

    A simple component with a simple render() method: 

     

    class Header extends React.Component {

      render() {

    return (

       <h1>This is the content of the Header component</h1>

    );

      }

    }

     

    ReactDOM.render(<Header />, document.getElementById(‘root’));

     

    componentDidMount

     

    The componentDidMount() method is called after the component is rendered. 

     

    This is the place where you run statements that require that the component is already placed on the DOM. 

     

    For Example: 

    In the first option, we put our favorite color as red, but within a second, it is yellow instead. 

     

     

    class Header extends React.Component {

      constructor(props) {

    super(props);

    this.state = {favoritecolor: “red”};

      }

      componentDidMount() {

    setTimeout(() => {

       this.setState({favoritecolor: “yellow”})

    }, 1000)

      }

      render() {

    return (

       <h1>My Favorite Color is {this.state.favoritecolor}</h1>

    );

      }

    }

     

    ReactDOM.render(<Header />, document.getElementById(‘root’));

     

    Updating-

     

    The next phase that comes in the lifecycle is when the component is updated. 

     

    A component is updated whenever there is a change in the component’s state or props. 

     

    React has five built-in methods that gets called, in this order when a component is updated:

     

     

    1)    getDerivedStateFromProps()

    2)    shouldComponentUpdate()

    3)    render()

    4)    getSnapshotBeforeUpdate()

    5)    componentDidUpdate()

     

    Once again, the render() method is required and will always be called, the others are optional and will be called only and only if you define them. 

     

    getDerivedStateFromProps-
     

    At the stage of updates, the getDerivedStateFromprops method is called. This is the first method that is called when a component gets updated. 

    This is the ideal place to set the state based on the initial props.

     

    The example below has a button that changes the favorite color to blue, but since the getDerivedStateFromProps() method is called, which updates the state with the color from the favcol attribute, the favorite color is still rendered as yellow:

     

    class Header extends React.Component {

      constructor(props) {

        super(props);

        this.state = {favoritecolor: “red”};

      }

      static getDerivedStateFromProps(props, state) {

        return {favoritecolor: props.favcol };

      }

      changeColor = () => {

        this.setState({favoritecolor: “blue”});

      }

      render() {

        return (

          <div>

          <h1>My Favorite Color is {this.state.favoritecolor}</h1>

          <button type=”button onClick={this.changeColor}>Change color</button>

          </div>

        );

      }

    }

     

    ReactDOM.render(<Header favcol=”yellow“/>, document.getElementById(‘root’));

     

    shouldComponentUpdate:

     

    In this method, you can return a Boolean value that specifies whether Reacy should continue with the rendering or not. 

     

    The default value is true. 

     

    The example given below shows what happens when the shouldComponentUpdate() method returns false:

     

    class Header extends React.Component {

      constructor(props) {

        super(props);

        this.state = {favoritecolor: “red”};

      }

      shouldComponentUpdate() {

        return false;

      }

      changeColor = () => {

        this.setState({favoritecolor: “blue”});

      }

      render() {

        return (

          <div>

          <h1>My Favorite Color is {this.state.favoritecolor}</h1>

          <button type=”button onClick={this.changeColor}>Change color</button>

          </div>

        );

      }

    }

     

    ReactDOM.render(<Header />, document.getElementById(‘root’));

     

    The next example shows what happens when the method returns true instead: 

    class Header extends React.Component {

      constructor(props) {

        super(props);

        this.state = {favoritecolor: “red”};

      }

      shouldComponentUpdate() {

        return true;

      }

      changeColor = () => {

        this.setState({favoritecolor: “blue”});

      }

      render() {

        return (

          <div>

          <h1>My Favorite Color is {this.state.favoritecolor}</h1>

          <button type=”button onClick={this.changeColor}>Change color</button>

          </div>

        );

      }

    }

     

    ReactDOM.render(<Header />, document.getElementById(‘root’));

     

    Render

    The render() method is of course called when a component gets updated, it has to re-render the HTML to the DOM, with the new changes. 

     

    The example below has a button that changes the favorite color to blue: 

     

    class Header extends React.Component {

      constructor(props) {

        super(props);

        this.state = {favoritecolor: “red”};

      }

      changeColor = () => {

        this.setState({favoritecolor: “blue”});

      }

      render() {

        return (

          <div>

          <h1>My Favorite Color is {this.state.favoritecolor}</h1>

          <button type=”button onClick={this.changeColor}>Change color</button>

          </div>

        );

      }

    }

     

    ReactDOM.render(<Header />, document.getElementById(‘root’));

     

     

    getSnapshotBeforeUpdate

     

    While using this method, you have access to the props and state before the update, meaning that even after the update, you can check what the values were before the update. 

     

    If this method is present, you should also include the componentDidUpdate() method, otherwise, you will get an error. 

     

    Follow the example below: 

     

    class Header extends React.Component {

      constructor(props) {

        super(props);

        this.state = {favoritecolor: “red”};

      }

      componentDidMount() {

        setTimeout(() => {

          this.setState({favoritecolor: “yellow”})

        }, 1000)

      }

      getSnapshotBeforeUpdate(prevProps, prevState) {

        document.getElementById(“div1”).innerHTML =

        “Before the update, the favorite was “ + prevState.favoritecolor;

      }

      componentDidUpdate() {

        document.getElementById(“div2”).innerHTML =

        “The updated favorite is “ + this.state.favoritecolor;

      }

      render() {

        return (

          <div>

            <h1>My Favorite Color is {this.state.favoritecolor}</h1>

            <div id=”div1“></div>

            <div id=”div2“></div>

          </div>

        );

      }

    }

     

    ReactDOM.render(<Header />, document.getElementById(‘root’));

     

    componentDidUpdate:

     

    The componentDidUpdate method is called after the component is updated in the DOM. 

     

    Follow the example below: 

     

    class Header extends React.Component {

      constructor(props) {

        super(props);

        this.state = {favoritecolor: “red”};

      }

      componentDidMount() {

        setTimeout(() => {

          this.setState({favoritecolor: “yellow”})

        }, 1000)

      }

      componentDidUpdate() {

        document.getElementById(“mydiv”).innerHTML =

        “The updated favorite is “ + this.state.favoritecolor;

      }

      render() {

        return (

          <div>

          <h1>My Favorite Color is {this.state.favoritecolor}</h1>

          <div id=”mydiv“></div>

          </div>

        );

      }

    }

     

    ReactDOM.render(<Header />, document.getElementById(‘root’));

     

    Unmounting:

     

    The next and last phase is unmounting, i.e. when the component is removed from the DOM. 

     

    React has only one built-in method that gets called when a component is unmounted:

     

          componentWillUnmount()

     

    componentWillUnmount-

     

    The componentWillUnmount method is called in right before the component is about to be removed from the DOM. 

     

    Follow the example:

     

    class Container extends React.Component {

      constructor(props) {

        super(props);

        this.state = {show: true};

      }

      delHeader = () => {

        this.setState({show: false});

      }

      render() {

        let myheader;

        if (this.state.show) {

          myheader = <Child />;

        };

        return (

          <div>

          {myheader}

          <button type=”button onClick={this.delHeader}>Delete Header</button>

          </div>

        );

      }

    }

     

    class Child extends React.Component {

      componentWillUnmount() {

        alert(“The component named Header is about to be unmounted.”);

      }

      render() {

        return (

          <h1>Hello World!</h1>

        );

      }

    }

     

    ReactDOM.render(<Container />, document.getElementById(‘root’));

     

    This completes the process of the React Lifecycle. 

     

    Recent Articles

    React Fragment: Find out what we encountered.!

      React Fragment: Hello Devs, in my journey of learning react I came across some frontend conditions where I had to render multiple react components,...

    React Admin: Documentation | Features | Dahboard | Templates

      React Admin is a framework for the front-end development of data-driven applications. That is operating in a browser over the top of REST or...

    React Hooks

      A hook is a component that allows us to use the features of React and state without defining a class. This feature is added...

    React Animation: A definitive guide

    React Animations Add-ons The ReactTransitionGroup add-on is a lower-level Applications Program Interface (API) component for creating react animations. And the ReactCSSTransitionGroup, is a component used...

    Create React App: A Complete guide for Beginners

      Create React App is the modern way of building an official Single Page React Application. It sets up a comfortable environment for building react...

    Related Stories

    Leave A Reply

    Please enter your comment!
    Please enter your name here