DEV Community

Sachin
Sachin

Posted on

React lifecycle methods

Each component in react live a life - from birth to death.
Main three stages of the lifecycle of a component are:

  1. Mounting : Birth of the component
  2. Updating : Growth of the component
  3. Unmounting : Death of the component

we have many method in these lifecycle, but i'm talk about four mostly used methods. These methods can only used in class components.

render()

render() {
    console.log('rendering')
    return (
        <div>
          <div>Parent Component</div>
        </div>);

         }
Enter fullscreen mode Exit fullscreen mode

Other ways can be used, but this one must be declared. Our component is created at this stage and is added to the DOM. Rendering of the component to the DOM

componentDidMount()

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


class... {
constructor(props) {
    super();

    this.state = {
        color : ''
    }
}

    componentDidMount() {
        this.setState({
            color: 'red'
        })
    }

    render() {
        <h1>I, a header element, is born! My color is {this.state.color}</h1>
    }

}

Enter fullscreen mode Exit fullscreen mode

componentdidupdate()

Once the update is complete, this method is called. It accepts as input the previous props, previous state. This is an ideal location for causing side effects and making network requests for the updated props.

 componentDidUpdate(prevProps) {
        if(this.props.color !== prevProps.color) {
            console.log('component updating')
        }
    }

Enter fullscreen mode Exit fullscreen mode

shouldComponentUpdate()

When state or props change, you'll want a component to re-render. You do, however, have control over this behaviour.
You can control whether the component is rerendered by returning a boolean (true or false) within this lifecycle method.

shouldComponentUpdate(){
    console.log('shouldComponentUpdate')
    return true
}
Enter fullscreen mode Exit fullscreen mode

Reference links

react js

log Rocket

Top comments (0)