Skip to main content

Command Palette

Search for a command to run...

Lifecycle Methods in React.Js 🧬

Let's Learn Lifecycle Of React Components In Depth

Updated
7 min readView as Markdown
Lifecycle Methods in React.Js 🧬
M

Software Engineer 👩🏻‍💻. Part Time Open-Source Developer 🐛

In this Blog, we’ll dive into the details of the mentioned lifecycle methods, explain how they’re divided, and how they can be used with hooks. Without further ado, let’s jump right in.

What is Lifecycle?

Each component in React has a lifecycle which you can monitor and manipulate during its three main phases.
In React, the Life cycle of a component represents the different stages of the component during its existence. React provides a callback function to attach functionality in every stage of the React Lifecycle.

The three phases are:

  • Mounting − Mounting represents the rendering of the React component in the given DOM node.

  • Updating − Updating represents the re-rendering of the React component in the given DOM node during state changes/updates.

  • Unmounting − Unmounting represents the removal of the React component.

Let's Dive Deep Into These Methods 1 by 1 🚀

1. Mounting:

Mounting means putting elements into the DOM.

React has four built-in methods that get called, in this order, when mounting a component:

  1. constructor() 🢂 The constructor() method is called before anything else when the component is initiated, and it is the natural place to set up the initial state and other initial values.

     class Header extends React.Component {
    
     // Constructor is Used to set initial state and properties of the  component.
       constructor(props) {
         super(props);  
         this.state = {favoritePlayer: "Messi"};
       }
    
       render() {
        return (
         <h1> My Favorite Football Player is {this.state.favoritePlayer} </h1>
         );
       }
     }
     //➤ My Favorite Football Player is Messi.
    

    The constructor() method is called with the props, as arguments, and you should always start by calling the super(props) before anything else, this will initiate the parent's constructor method and allows the component to inherit methods from its parent (React.Component).

  2. getDerivedStateFromProps() 🢂 The getDerivedStateFromProps() method is called right before rendering the element(s) in the DOM.

     class Header extends React.Component {
    
       constructor(props) {
         super(props);
         this.state = {favoritecolor: "red"};
       }
    
     // The example below starts with the favorite color being "red", but the getDerivedStateFromProps() method updates the favorite color based on the favcol attribute:
       static getDerivedStateFromProps(props, state) {
         return {favoritecolor: props.favcol };
       }
    
       render() {
         return (
           <h1>My Favorite Color is {this.state.favoritecolor}</h1>
         );
       }
     }
    

    This is the natural place to set the state object based on the initial props. It takes state as an argument, and returns an object with changes to the state.

  3. render() 🢂 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>
         );
       }
     }
    

    The render() method is required and is the method that actually outputs the HTML to the DOM.

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

     class Header extends React.Component {
       constructor(props) {
         super(props);
         this.state = {favoritePlayer: "Ronaldo"};
       }
    
     // After Rendering the component into the DOM the 'favoritePlayer' will change 'Messi' from 'Ronaldo' after 1 Second.
       componentDidMount() {
         setTimeout(() => {
           this.setState({favoritePlayer: "Messi"})
         }, 1000)
       }
       render() {
         return (
           <h1>My Favorite Football Player is {this.state.favoritePlayer}</h1>
         );
       }
     }
    

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

2. Updating:

The next phase in the lifecycle is when a 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 get called, in this order, when a component is updated :

  • getDerivedStateFromProps() ✔ already covered

  • shouldComponentUpdate() − In the shouldComponentUpdate() method you can return a Boolean value that specifies whether React should continue with the rendering or not. The default value is true.

  • render() ✔ already covered

  • getSnapshotBeforeUpdate() − It is mainly used to get some information about the new content. The data returned by this method will be passed to ComponentDidUpdate() method.

  • componentDidUpdate() − The componentDidUpdate method is called after the component is updated in the DOM.

Let's Get Into These Methods 1 by 1:

  1. shouldComponentUpdate() 🢂 the shouldComponentUpdate() method you can return a Boolean value that specifies whether React should continue with the rendering or not. The default value is true.

    Let's say we want to Stop the component from rendering at any update:

     class Header extends React.Component {
       constructor(props) {
         super(props);
         this.state = {favoritecolor: "red"};
       }
    
     // This Component Won't be Updated. But If you want to Update the Component Just Change 'false' to 'true'.
       shouldComponentUpdate() {
         return false;
       }
    
       changeColor = () => {
         this.setState({favoritecolor: "blue"});
       }
       render() {
         return (
          <div>
            <h1> My Favorite Color is {this.state.favoritecolor} </h1>
             <button onClick={this.changeColor}> Changecolor </button>
          </div>
         );
       }
     }
    

    The example above shows what happens when the shouldComponentUpdate() method returns false, you can set it to true if you want to update.

  2. getSnapshotBeforeUpdate() 🢂 In the getSnapshotBeforeUpdate() 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 the getSnapshotBeforeUpdate() method is present, you should also include the componentDidUpdate() method, otherwise you will get an error. Explanation 👇🏻

     class Header extends React.Component {
     // When the component is mounting it is rendered with the favorite color "red".
       constructor(props) {
         super(props);
         this.state = {favoritecolor: "red"};
       }
    
     // When the component has been mounted, a timer changes the state, and after one second, the favorite color becomes "yellow".
       componentDidMount() {
         setTimeout(() => {
           this.setState({favoritecolor: "yellow"})
         }, 1000)
       }
    
     // This action triggers the update phase, and since this component has a getSnapshotBeforeUpdate() method, this method is executed, and writes a message to the empty DIV1 element.
       getSnapshotBeforeUpdate(prevProps, prevState) {
         document.getElementById("div1").innerHTML =
         "Before the update, the favorite was " + prevState.favoritecolor;
       }
    
     // Then the componentDidUpdate() method is executed and writes a message in the empty DIV2 element:
       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>
         );
       }
     }
    

    I hope that the example above makes sense to you, lemme know in the comments.

  3. componentDidUpdate() 🢂 The componentDidUpdate method is called after the component is updated in the DOM.

     class Header extends React.Component {
     // When the component is mounting it is rendered with the favorite color "red".
       constructor(props) {
         super(props);
         this.state = {favoritecolor: "red"};
       }
    
     // When the component has been mounted, a timer changes the state, and the color becomes "yellow".
       componentDidMount() {
         setTimeout(() => {
           this.setState({favoritecolor: "yellow"})
         }, 1000)
       }
    
     // This action triggers the update phase, and since this component has a componentDidUpdate method, this method is executed and writes a message in the empty DIV element:
       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>
         );
       }
     }
    

    I hope that the example above is clear :)

3. Unmounting

  1. The next phase in the lifecycle is when a component is removed from the DOM, or unmounting as React likes to call it.

    React has only one built-in method that gets called when a component is unmounted and that is componentWillUnmount().

    • componentWillUnmount() 🢂 The componentWillUnmount() method is called when the component is about to be removed from the DOM.

        class Container extends React.Component {
          constructor(props) {
            super(props);
            this.state = {show: true};
          }
        // Delete Header Function
          delHeader = () => {
            this.setState({show: false});
          }
      
          render() {
            let myheader;
            if (this.state.show) {
              myheader = <Child />;
            };
            return (
               <div>
                {myheader}
                <button onClick={this.delHeader}> Delete Header </button>
              </div>
            );
          }
        }
      
        // This Child component will be Deleted from the DOM.
        class Child extends React.Component {
          componentWillUnmount() {
            alert("The component named Header is about to be unmounted.");
          }
          render() {
            return (
              <h1>Hello World!</h1>
            );
          }
        }
      

      When You Click on the Button it'll delete the Child component from DOM.

Conclusion

That's it For the Article

I hope you learned something about these important Lifecycle Methods in React

If you need any help please feel free to ping me in the comments section.

Let's connect on Twitter and LinkedIn.

Thanks for reading, See you next time 👋