DEV Community

Cover image for React Components Lifecycle Methods - WTH are they?
Aditya Shukla
Aditya Shukla

Posted on

React Components Lifecycle Methods - WTH are they?

Introduction πŸ‘‹

Every component in React has it's own lifecycle. But before going in depth to that, πŸ€” we should know what exactly is Lifecycle of a React Component, and why do I need to know it?

Question

A Lifecycle is nothing but a sequence of methods that are executed at different stages of the component's existence. Each react component has several "Lifecycle Methods". We need to know these methods so that we can override them when we want to run some code at a particular time in the process.

🌱 Phases of a React Component

There are 4 Phases of a Component:

  1. Mounting : During this phase, the Component is initialized and the inserted into the DOM.
  2. Updating : If there is already a Component rendered on the DOM, then any updates are done to the Component as part of the Updating phase.
  3. Error Handling: This Phase is responsible for taking care of the error found during rendering in lifecycle method or in the constructor or any other child components.
  4. Unmounting: During this phase, removing of component from the DOM as well as cleanup activities are done.

React Lifecycle Methods

🧬 Lifecycle Methods

Now that we know the different phases of a React Component, lets now try to understand the different Lifecycle Methods that are invoked during each phase.

1. πŸ‡ Mounting Phase:

At this phase the Component is created with props and state which are initialized within a constructor. Once ready with props and state, the component is ready to mount on to the DOM and is rendered for the first time on the web page.

The methods in the Mounting Phase are:

1. constructor():

  • This is the first method that is called for any component.
  • The main purpose of constructor is to initialize the props and state. Along with that, it also binds the events with 'this' i.e. the Instance.
  • The constructor includes a call to the super() along with the initialization of this.state.
  • One thing to keep in mind is that, the initialization of the state can be done without the constructor() method too and it'll work the same.
  import React from 'react';

  class AppComp extends React.Component {
        constructor(props) {
                super(props);
                this.state = {
                        title : 'Lifecycle Methods'
                }
                console.log('Inside React Component 
  Constructor');
          }
  }
Enter fullscreen mode Exit fullscreen mode

2. getDerivedStateFromProps()

  • Just before rendering the component on the DOM, getDerivedStateFromProps method is called.
  • This method is called when the state of the component depends on the props.
  • Basically, this method allows the component to change it's state when there is any change in the props.
  • This is used very rarely, but its important to understand it's the order of execution as this method is called in Mounting Phase as well as in Updating phase.

Continuing the above code snippet:

  import React from 'react';

  class AppComp extends React.Component {
        constructor(props) {
                super(props);
                this.state = {
                        title : 'Lifecycle Methods'
                }
                console.log('Inside React Component 
  Constructor');
          }

        static getDerivedStateFromProps(props, state) {
                console.log('Inside React Component
                        getDerivedStateFromProps');
          }
  }
Enter fullscreen mode Exit fullscreen mode

3. render()

  • We write the JSX code inside this method which will be rendered on the DOM.
  • This is the only method that is required when we are creating a Component in React.
  • This method does not modify the state, it simply returns the same result each time it is invoked.
  • render() method observes the props and state values and it returns either of the following:
    • React Element
    • Array
    • Fragment
    • Strings, numbers, booleans or null
  import React from 'react';

  class AppComp extends React.Component {
        constructor(props) {
                super(props);
                this.state = {
                        title : 'Lifecycle Methods'
                }
                console.log('Inside React Component 
  Constructor');
          }

        static getDerivedStateFromProps(props, state) {
                console.log('Inside React Component
                        getDerivedStateFromProps');
          }

        render() {
                console.log('Inside render method');
                return <div> This is the App Component </div>
        }          
  }
Enter fullscreen mode Exit fullscreen mode

4. componentDidMount()

  • As soon as the component is mounted / inserted into the DOM tree, this method gets called.
  • Unlike render(), this method is called only once and that too on the Mounting phase. This makes this method the most suitable place for loading data from remote endpoints or making a network request.
  • We can even call the setState() method from within this method to modify the state and ultimately recall the render() to update the contents of the DOM.
  • This method ensures that the user won't see any intermediate states even though render() method is called twice.
  import React from 'react';

  class AppComp extends React.Component {
        constructor(props) {
                super(props);
                this.state = {
                        title : 'Lifecycle Methods'
                }
                console.log('Inside React Component 
  Constructor');
          }

        static getDerivedStateFromProps(props, state) {
                console.log('Inside React Component
                        getDerivedStateFromProps');
          }

        componentDidMount(){  
                  console.log("Inside componentDidMount");
         }

        render() {
                console.log('Inside render method');
                return <div> This is the App Component </div>
        }          
  }
Enter fullscreen mode Exit fullscreen mode

Console Output for the above code:
Console Output

Still With Me here? Hold on a bit
lets go

Now, let's see the 2nd Phase of a Component's Lifecycle

2. πŸ‘¨β€πŸ’» Updating Phase:

  • Whenever there is a change in the state of the component, the component's lifecycle comes inside the Updating phase.
  • Some of the methods are common in the Mounting and Updating phase, this is because these same methods are called again during this phase. These methods are:
    • getDerivedStateFromProps(), and
    • render()
  • Including these methods, there are a total of 5 methods in the Updating phase. Let's look at them one by one

1. static getDerivedStateFromProps()

  • In the Updating phase of the component this method is called whenever the component receives new props, or whenever the setState() method is called to updated the existing state.
  • One thing needs to be made sure here is that there should be no HTTP requests or Ajax calls etc. be made in this method.

2. shouldComponentUpdate()

  • This method is called whenever there is a change in the state.
  • It decides if the component should be re-rendered or not as it is called right before the render() method when new props or state are received.
  • Since it is only called when there is a change in the existing state, this method was not present in the Mounting phase.
  • It takes in the nextProps and nextState as the function parameters, which looks like this:

shouldComponentUpdate(nextProps, nextState)

  • If this method returns false, it notifies React that the update can be skipped.

3. render()

  • The functioning of the render() method in the Updating phase is same as that of in the Mounting phase.

4. getSnapshotBeforeUpdate()

  • This method is called right before any changes are going to be updated in Real DOM from virtual DOM.
  • It is used to capture some information from DOM. Example: Observing the scroll position, etc.
  • It is the final call to check the data with its previous state/props.
  • This method will either return a value or null. Whatever the return value is, it will be passed as the 3rd parameter to the next method.

5. componentDidUpdate()

  • This is the final method of the Updating phase.
  • It is called after all the changes are updated in the DOM.
  • The syntax for this is as follows:

componentDidUpdate(prevProps, prevState, snapShot)

  • The 3rd parameter i.e. the snapshot is the value which was returned by the getSnapshotBeforeUpdate() method.

Let's see the below code to understand the Updating phase:

Child.js:

import React, { Component } from 'react';  

class Child extends Component{  
        constructor(props){  
                super(props);  
                this.state={  
                        value:'React Application'  
                }  
                console.log("Inside child constructor");  
        }  

        static getDerivedStateFromProps(props,state){  
                console.log("Inside child getDerivedStateFromProps");  
                return null;  
        }  

        componentDidMount(){  
                console.log("Inside child componentDidMount");  
         }  

        shouldComponentUpdate(){  
                console.log("Inside child shouldComponentUpdate");  
                return true;  
        }  

        getSnapshotBeforeUpdate(prevProps,prevState){  
                console.log("inside child getSnapshotBeforeUpdate");  
                return null;  
        }  

        componentDidUpdate(){  
                console.log("Inside child componentDidUpdate");  
        }  

        render(){  
                console.log("Inside child render");  
                return <div/>  
        }  
}  

export default LifecycleChild;
Enter fullscreen mode Exit fullscreen mode

App.js

import React,{Component} from 'react';  
import Child from './Child';  

class App extends Component{  
        constructor(props){  
                super(props);  
                this.state={  
                        value:'React Application'  
                }  
                this.changeState = this.changeState.bind(this);  
                console.log("Inside constructor");  
        }  

        static getDerivedStateFromProps(props,state){  
                console.log("Inside getDerivedStateFromProps");  
                return null;  
        }  

        componentDidMount(){  
                console.log("Inside componentDidMount");  
        }  

        shouldComponentUpdate(){  
                console.log("Inside shouldComponentUpdate");  
                return true;  
        }  

        getSnapshotBeforeUpdate(prevProps,prevState){  
                console.log("Inside getSnapshotBeforeUpdate");  
                return null;  
        }  

        componentDidUpdate(){  
                console.log("Inside componentDidUpdate");  
        }  

        changeState = () => {   
                this.setState({  
                        value : "React Application started"  
                })  
        }  

        render(){  
                console.log("Inside render");  
                return(  
                        <div>  
                                <div>React Parent</div>  
                                <button onClick={this.changeState}>Click Me</button>  
                                <Child />
                        </div>  
                );  
        }  
}  

export default App; 
Enter fullscreen mode Exit fullscreen mode

Console Outputs:

  1. During Mounting..

On Mount

  1. During Updating (On clicking the "Click Me")...

On Update

Notice that all the console outputs are in the order for all the methods as per the lifecycle. But there is a small different in calling of getSnapshotBeforeUpdate().
For the getSnapshotBeforeUpdate() method, the child's method is called before the Parent's method. Once called, all the other Parent's methods are called.

Note: Even thoght we saw 5 methods for the updating phase, the most used ones are the render() and componentDidUpdate(), out of which render() is the only method which is mandatory.

3. πŸ₯‚ Unmounting Phase

  • The React component enters this phase after going through the Updating phase, when the component is removed from the DOM.
  • This phase as only 1 method, which is:

componentWillUnmount()

  • This method is called just before the Component is removed from the DOM. This removal can be unmounting or being destroyed.
  • We need to make sure of one thing that is, the setState() method should never be called inside this method.
  • The reason for this is, the componentWillUnmount() method is the last stage of the lifecycle of any React Component, once it is unmounted it will never be mounted again. And the setState() method re-renders the contents on the DOM, so it will not be possible.
  • Usage: This method can be used for Clean up process. For example, closing any open connections, or cancelling any network requests or removing any event handlers, etc.

Summary:

So during the lifecycle of any React Component, it goes through different phases, these phases are Mounting, Updating and Unmounting phase. There is another phase called as Error Handling phase which also contains two methods: getDerivedStateFromError() and componentDidCatch().

Thanks for Reading.. πŸ”š

Top comments (1)

Collapse
 
janpauldahlke profile image
jan paul

This is how i learned to "react" back int the days. Nowadays there is this egg-laying woolly milk sow, useEffect=(() => {},[])