Author -  Sai gowtham

A Beginners Guide to React Lifecycle methods

In this tutorial, we will learn about how to use the lifecycle methods in react.

In react each component has a different type of a lifecycle methods that are invoked at the different phases.like when a component is created, inserted and a component is updated or removed from the dom.

Simple definition : React offers us a custom methods which are called different times during the component birth to death.

componentDidMount()

This method is invoked after the component is mounted to the dom tree this a good place to make network requests.

example :

import React,{Component} from 'react'
import axios from 'axios';

class App extends Component{

state = {
   todo:null
}


componentDidMount(){
  axios.get('https://jsonplaceholder.typicode.com/todos/1')
  .then(res=>{
      this.setState({
          todo:res.data
      })
  })
  .catch(err=>console.log(err))
}

    render(){
        return (
            <div>
            <h1>Http requests in react</h1>
            {this.state.todo ? <p>{this.state.todo.title}</p>
            : <p>Loading...</p>}
            </div>
        )
    }

}

shouldComponentUpdate(nextProps,nextState)

  • shouldComponentUpdate method only re-renders the component if an state or props are updated.

  • This method is invoked before an update occurs by default it returns false. This method is not called for the initial render or when a forceUpdate() method is used.

example:

class App extends React.Component {
  state = {
    num:0
  };

  handleClick = () => {
      this.setState({
        num: Math.floor(Math.random() * 3 + 1),
      })

  };

  shouldComponentUpdate(nextProps, nextState) {
     if(this.state.num !== nextState.num){
       return true
     }
       return false
  }
  render() {
    return (
      <div>
        shouldComponentUpdate
         <br/>
        <p> {this.state.num}</p>
        <button onClick={this.handleClick}>Random</button>
      </div>
    );
  }
}

In the above code we only re-renders the App component if the previous state.number is not equal to the next state.number.

componentDidUpdate()

This method is invoked immediately after a component is updated and also it is not invoked on the initial render.

componentDidUpdate() method is not invoked if shouldComponentUpdate() method return false.


componentDidUpdate(nextProps, nextState){

   if(this.state.auth !== nextState.auth){
       this.router.push('/login')
   }

}

In the above we used componentDidUpdate method to push the user to the login page in case he or she is logged out.

componentwillUnmount

This method is invoked just before a component is unmounted from the DOM. This is the ideal place to perform cleanup and canceling network requests, clearing timers.

example:

componentDidMount() {
    document.addEventListener("mousemove", this.handleMove);
    document.addEventListener("mouseup", this.handleDown);
  }

  componentWillUnmount() {
    document.removeEventListener("mousemove", this.handleMove);
    document.removeEventListener("mouseup", this.handleDown);
  }

Css Tutorials & Demos

How rotate an image continuously in CSS

In this demo, we are going to learn about how to rotate an image continuously using the css animations.

How to create a Instagram login Page

In this demo, i will show you how to create a instagram login page using html and css.

How to create a pulse animation in CSS

In this demo, i will show you how to create a pulse animation using css.

Creating a snowfall animation using css and JavaScript

In this demo, i will show you how to create a snow fall animation using css and JavaScript.

Top Udemy Courses

JavaScript - The Complete Guide 2023 (Beginner + Advanced)
JavaScript - The Complete Guide 2023 (Beginner + Advanced)
116,648 students enrolled
52 hours of video content
$14.99 FROM UDEMY
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
631,582 students enrolled
49 hours of video content
$24.99 FROM UDEMY
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
203,937 students enrolled
31.5 hours of video content
$14.99 FROM UDEMY