React JS lifecycle methods contain three lifecycle stages in a React app. Mosh Hamedani says it best: it is a cycle from the birth of a component to its death. Let’s dive deeper.

Birth of the component – Mounting stage

Growth of the component – Updating stage

Death of the component – Unmount stage

Common React JS lifecycle methods

render()

class Hello extends Component{
   render(){
      return <div>Hello World!</div>
   }
}

This method is used in all React Components this is because render() is the only required method within a class component in React. The render() method returns JSX which is displayed in the UI. Execution of this method happens at the mounting and updating stage of your component.

Beware: you cannot modify the component state in the render() method!

React requires your render() method to be pure. Pure functions are those that do not contain side-effects. If you do need to modify the state it would have to happen in the other lifecycle methods.

componentDidMount()

Your component has been mounted and is ready: that’s when the React lifecycle method componentDidMount() comes in.

componentDidMount() is called when the component is mounted and ready. This is a good place to initiate API calls.

componentDidMount() allows the use of setState() . When calling setState() the state will be updated and cause re-rendering before the browser loads the UI.

It is recommended that you use this method with caution as it will lead to performance issues. The best practice is to ensure that your states are assigned in the constructor.

The reason why React allows for the setState() functionality is for special cases such as tooltips, modals and similar concepts when you need to measure a DOM node before rendering something.

import React, { Component } from 'react';

class App extends Component {

  constructor(props){
    super(props);
    this.state = {
      data: 'Jordan Belfort'
    }
  }

  getData(){
    setTimeout(() => {
      console.log('Our data is fetched');
      this.setState({
        data: 'Hello Wall Street'
      })
    }, 1000)
  }

  componentDidMount(){
    this.getData();
  }

  render() {
    return(
      <div>
      {this.state.data}
    </div>
    )
  }
}

export default App;

componentDidUpdate()

componentDidUpdate(prevProps) {
 //Typical usage, don't forget to compare the props
 if (this.props.password !== prevProps.password) {
   this.fetchData(this.props.password);
 }
}

This lifecycle method is executed as soon as the updating happens. The most common use case for the componentDidMount() method is updating the DOM in response to prop or state changes.

You are able to use the setState() method at this lifecycle stage. However keep in mind you will have to invoke it in a condition to check for state or prop changes from the previous state.

Incorrect usage of setState() may lead to an infinite loop.

componentWillUnmount()

This lifecycle method is called just before the component is unmounted and destroyed. If there are any clean-up actions you need to perform then this method is perfect for that!

You cannot modify the component state using the setState() method in this lifecycle method. This is because the component cannot be re-rendered at this lifecycle method.

componentWillUnmount() {
 window.removeUploadListener('upload', this.uploadListener)
}

Common clean-up activities performed in this lifecycle method include, clearing timers, cancelling api calls and removing caches in storage.

This diagram below showcases the different React lifecycle methods and when they are invoked. Picture is from the official React documentation.

Uncommon React JS lifecycle methods

shouldComponentUpdate()

This method is useful for when you don’t want React to render your prop or state changes.

Anytime setState() method is called, the component will re-render by default. This lifecycle method is used to let React know that the component is not affected by state and prop changes.

Beware: this lifecycle method should be used sparingly and it exists only for certain performance optimisations.

You cannot use the setState() method in this lifecycle method.

shouldComponentUpdate(nextProps, nextState) {
  return this.props.description !== nextProps.description || 
  this.state.input !== nextState.input 
}

In the above code snippet, this method should always return a boolean value to the question “Should I re-render the component?”

static getDerivedStateFromProps()

This method is quite new and was recently introduced by the React team!

This method is a safer alternative to the previous lifecycle method componentWillRecieveProps(). This method is invoked just before the render() method. ComponentWillRecieveProps() is only implemented for rare use cases where the state depends on prop changes in a component.

static getDerivedStateFromProps(props, state) {
    if (props.currentRow !== state.lastRow) {
      return {
        isScrollingDown: props.currentRow > state.lastRow,
        lastRow: props.currentRow,
      };
    }
    // Return null to indicate no change to state.
    return null;
  }

This is a static function that does not have access to “this“. GetDerivedStateFromProps() returns an object to update state in response to prop changes. It can return null if there are no changes to state.

This method above would be great for a TransitionAnimation component to come in that compares its previous and next elements to decide which ones to animate-in and animate-out.

getSnapshotBeforeUpdate()

This is also a newer method released by the React team. This method will be a safer alternative to the previous lifecycle method componentWillUpdate().

getSnapshotBeforeUpdate(prevProps, prevState) {
    // ...code
  }

This lifecycle method is called just before the DOM is updated. The value that is returned from this method is passed onto the componentDidUpdate() method. Use this method sparingly or don’t use it at all.