My FeedDiscussionsHeadless CMS
New
Sign in
Log inSign up
Learn more about Hashnode Headless CMSHashnode Headless CMS
Collaborate seamlessly with Hashnode Headless CMS for Enterprise.
Upgrade ✨Learn more

Lifecycle Methods in React

Srividya Mysore Venkatesh's photo
Srividya Mysore Venkatesh
·Aug 31, 2021·

5 min read

Lifecycle Methods in React

Just like we study the Lifecycle in the Biosphere. We can think of Lifecycle Methods in React, to be somewhat similar.

We can call, React lifecycle methods as the series of events that happen from the birth of a React component to its death.

  • Mounting – Birth of your component - or insertion into the DOM
  • Update – Growth of your component - manipulating it in the DOM
  • Unmount – Death of your component - or removal from the DOM

There are many React Lifecycle Methods but in this blog, I'd like to only write about some of the most commonly used ones:

  • constructor() - this method is called even before the component is mounted. Technically Constructor is used for two main purposes:
    • Initializing local state by assigning an object to this.state
    • Binding event handler methods to an instance.

Moreover, When implementing the constructor for a React.Component subclass, you should call "super(props)" before any other statement. Otherwise, this.props will be undefined in the constructor, which can lead to bugs.

NOTE: Constructor is the only place where you should assign this.state directly. In all other methods, you need to use this.setState() instead.

and you can not use setState() in the constructor. Instead, use this.state() to locally access the state.

import React, { Component } from 'react'

export default class App extends Component {
  constructor(props){
    super(props)
    this.state = {
      name: 'Constructor Method'
    }
  }
  render() {
    return (
      <div>
       <p> This is a {this.state.name}</p>
      </div>
    )
  }
}
  • render() - The render() method is the most used lifecycle method. This is because render() is the only required method within a class component in React. As the name suggests it handles the rendering of your component to the UI. It happens during the mounting and/or updating of your component.
import React, { Component } from 'react'

export default class renderMethod extends Component {
    render() {
        return (
            <>
                 <p>This is a render method</p>
            </>
        )
    }
}

the render() method returns JSX that is displayed in the UI. A render() can also return a null if there is nothing to render for that component.

the render method needs to be Pure with no side effects. Pure functions are those that do not have any side effects and will always return the same output when the same inputs are passed. This means that you can not setState() within a render().

  • componentDidMount() - Well now that the component is mounted with render(), that’s when the next React lifecycle method componentDidMount() does a waltz into the scene.

componentDidMount() is called as soon as the component is mounted and ready. This is a good place to initiate API calls, if you need to load data.

Unlike the render() method, componentDidMount() allows the use of setState(). Calling the setState() here will update state and cause another rendering but it will happen before the browser updates the UI. This is to ensure that the user will not see any UI updates with the double rendering.

import React, { Component } from 'react'

export default class componentDidMountMethod extends Component {
  constructor(props){
    super(props)
    this.state = {
      name: 'This name will change in 5 sec'
    }
  }
  componentDidMount() {
    setTimeout(() => {
      this.setState({name: "This is a componentDidMount Method"})
    }, 5000)

  }
  render() {
    return (
      <div>
       <p>{this.state.name}</p>
      </div>
    )
  }
}
  • componentDidUpdate() - This lifecycle method is invoked as soon as the updating happens. The most common use case for the componentDidUpdate() method is updating the DOM in response to prop or state changes.

You can call setState() in this lifecycle, but keep in mind that you will need to wrap it in a condition to check for state or prop changes from the previous state. If the setState() is used incorrectly might lead to slipping into an infinite loop.

import React, { Component } from 'react'

export default class componentDidUpdateMethod extends Component {
    constructor(props){
        super(props)
        this.state = {
            name: 'from previous state'
        }
    }
    componentDidMount(){
        setTimeout(() => {
            this.setState({name: "to current state"})
          }, 5000)
    }
    componentDidUpdate(prevState){
        if(prevState.name !== this.state.name){
            document.getElementById('statechange').innerHTML = "Yes the state is changed"
        }
    }
    render() {
        return (
            <div>
                State was changed {this.state.name}
                <p id="statechange"></p>
            </div>
        )
    }
}
  • componentWillUnmount() - As the name suggests this lifecycle method is called just before the component is unmounted and destroyed. If there are any cleanup actions that you would need to do, this would be the right spot.

The state will never be set under this method.

import React, { Component } from 'react'

export default class componentWillUnmount extends Component {
    constructor(props){
        super(props)
            this.state = {
                show: true,
            } 
    }
    render() {
        return (
            <>
              <p>{this.state.show ? <Child/> : null}</p>
               <button onClick={() => {this.setState({show: !this.state.show})}}>Click me to toggle</button>
            </>
        )
    }
}

export class Child extends Component{
    componentWillUnmount(){
        alert('This will unmount')
    }
    render(){
        return(
            <>
            I am a child component
            </>
        )
    }
}

Let me write about the flow, alt text img src: React Docs.

it is important to note that the render method is called more than once every time a component is mounted or updated.

lesser known lifecycle methods

  • getDerivedStateFromProps() - The getDerivedStateFromProps method is called right before rendering the element in our DOM. It takes props and state as an argument and returns an object with changes to the state.
import React, { Component } from 'react'

export class ChildComponent extends Component {
    constructor(props){
        super(props)
        this.state = {
          name: 'Constructor Method'
        }
      }

    static getDerivedStateFromProps(props, state) {
        return {name: props.nameFromParent} 
      }
    render() {
        return (
            <div>
                This is a {this.state.name}
            </div>
        )
    }
}


export default class getDerivedStateFromPropsMethod extends Component {

    render() {
        return (
            <div>
                <ChildComponent nameFromParent="getDerivedStateFromProps Method"/>
            </div>
        )
    }
}
  • shouldComponentUpdate() - This lifecycle method is used when you want your state or props to update or not. This method returns a boolean value that specifies whether rendering should be done or not. The default value is true.
import React, { Component } from 'react'

export default class shouldComponentUpdateMethod extends Component {
  constructor(props){
    super(props)
    this.state = {
      name: 'shouldComponentUpdate Method'
    }
  }
  shouldComponentUpdate() {
    return false; //Change to true for state to update
  }

  componentDidMount(){
    setTimeout(() => {
      this.setState({name: "componentDidMount Method"})
    }, 5000)
  }
  render() {
    return (
      <div>
       <p>This is a {this.state.name}</p>
      </div>
    )
  }
}