Life Cycle Methods in React

  • By
  • May 29, 2023
  • JavaScript
Life Cycle Methods in React

Life Cycle Methods in React

Every React application is made up of a number of components. These components run in whatever sequence is given to them to run. All components of React application have their own life cycle. The Life Cycle Methods in React of a component are nothing but different methods used during different stages of a component. Any react component goes through four stages of the life cycle. These stages of the life cycle are as follows:-

  1. Initialization
  2. Mounting
  3. Updating
  4. Unmounting

The stages of these life cycle methods in detail are as follows:-

For Free Demo classes Call: 8237077325

Registration Link: Click Here!

Note:

 

  • Initialization:- This is the first stage of life cycle in a class component. In this stage, the component is constructed with props and default state using the constructor method.

e.g. class Student extends Component

{

constructor()

{

this.state={

name: “AAA”

}

}

}

  • Mounting:-  This method of the life cycle is invoked after the initialization stage is completed. In this stage the component is first time rendered on the web page and the component is mounted on the DOM(Document Object Model). This stage uses some predefined functions like componentWillMount() , componentDidMount() and render() also. componentWillMount() will be executed before render() and componentDidMount() will be executed after render(). These are the compulsory phases of life that occur during component creation.

 

  • Updating:-  In React while creating a web application we create a number of components. From those components some are parents and some are child components. To send data from parent to child component we are using props. Class components also use state which is a built-in object of a class component. We can update props and state also. These states and props are updated using some events like a mouse click in React. So this is the updating phase of the life cycle. The following methods are called when a component is updated.
  • getDerivedStateFromProps()
  • shouldComponentUpdate()
  • render()
  • getSnapshotBeforeUpdate()
  • componentDidUpdate()

getDerivedStateFromProps() method is called before render. This method is used to set the state object based on props.

e.g. import React, { Component } from ‘react’

 

export default class GetderivedChild extends Component {

    constructor()

 {

    super()

    this.state={

        qty:0

    }

 }  

static getDerivedStateFromProps(props,state)

{

    console.log(props,state)

    return {

        qty:props.cnt*10

    }

}

  render() {

    console.log(“render”)

    return (

      <div>

        <h2>Get Derived State From Child Component</h2>

        <h3>Quantity of Product: {this.state.qty}</h3>

      </div>

    )  }}

shouldComponentUpdate() method returns a Boolean value which specifies whether to continue with rendering or not. Default value is true.

For Free Demo classes Call: 8237077325

Registration Link: Click Here!

Life Cycle Methods in React

 

e.g.

import React, { Component } from ‘react’

export default class Home extends Component {

    constructor()

    {

        super()

        this.state={

            price:2

        }

    }

 shouldComponentUpdate(prestate)

 {

    // if(prestate.price==this.state.price)

    // {

    // return false

    // }

    // return true

    if(this.state.price>50)

    {

    return false

    }

    return true

 }

  render() {

    console.log(“Render method”)

    return (

      <div style={{backgroundColor:”pink”,color:”purple”}}>

        <h1>Should Component Update Method {this.state.price}</h1>

        <button onClick={()=>this.setState({price:this.state.price*5})}>Update state</button>

      </div>

    )

  }

}

render() method adds HTML elements to the DOM.

getSnapshotBeforeUpdate() method is used with props and state before the update. After updating also you can check what were the values before the update. ComponentDidMount() method must be used with this method. 

import React, { Component } from ‘react’

 

export default class Child extends Component {

    constructor()

    {

        super()

        this.state={

            data:0

        }

    }

    componentDidUpdate(props,state,snapshot)

    {

        console.log(props,state,snapshot)

    }

    getSnapshotBeforeUpdate(preprop,prestate)

    {

        console.log(preprop)

        return prestate.data*5

    }

 

  render() {

    return (

      <div>

        {/* <h2>Child Component {this.props.num}</h2> */}

        <h2>Child Component {this.state.data}</h2>

        <button onClick={()=>this.setState({data:this.state.data+1})}>Update state</button>

      </div>

    )

  }

}

componentDidUpdate() is called after component is updated.

import React, { Component } from ‘react’

export default class Didupdate extends Component {  

constructor()

{

    super()

    this.state={

        counter:0

    }

}

  render() {

    return (

      <div>

        <h1>Component Did Update</h1>

        <h2>Counter:{this.state.counter}</h2>

        <Child data={this.state.counter}/>

        <button onClick={()=>this.setState({counter:this.state.counter+1})}>Update Counter</button>

       

      </div>

    )

  }

}

 

class Child extends Didupdate {

  

    constructor()

    {

        super()

        this.state={

            counter:0

        }

    }

    componentDidUpdate(pP,pS,sS)

    {

        console.log(“Method called”,pP,this.props.data)

        

    }

      render() {

        return (

          <div>

            <h1>Child component</h1>

            <h2>Counter:{this.props.data}</h2>           

          </div>

        )

      }

    }

For Free Demo classes Call: 8237077325

Registration Link: Click Here!

 

  • Unmounting:- 

This is the last phase in the life cycle methods of React component. This phase will un mount the component from the DOM. Before unmounting the component from the DOM componentWillUnmount() function is invoked.

e.g. import React, { Component } from ‘react’

 

export default class Employee extends Component {

  

componentWillUnmount()

{

    console.warn(“componentWillUnmount”)

}

  render() {

    return (

      <div>

        <h1>Employee Component</h1>

      </div>

    )

  }

These are the life cycle methods of a class component. For a functional component useEffect() hook is a life cycle method because it is called when a component is created when a component is called, when props are sent, and when props are updated.

Note: Supercharge your web development skills with our React JS classes in Pune! Gain hands-on experience in building dynamic and interactive web applications using the popular React framework.

Do visit our Channel: Click Here

Author:-

Sarika Ganesh Kore

Call the Trainer and Book your free demo Class For React JS Call now!!!
| SevenMentor Pvt Ltd.

© Copyright 2021 | SevenMentor Pvt Ltd.

Submit Comment

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

*
*