React Lifecycle methods with examples

Manish Mandal
How To React
Published in
6 min readSep 29, 2020

Let’s learn about the react life cycle method and how to use them in our react projects.

As everything goes through a cycle of taking birth, growing, and death the same goes with React. Each component in React has a lifecycle that goes through three main phases Mounting, Updating, and Unmounting.

The react lifecycle method is used in the React class component. It helps us in creating our state and mutating them. Below are diagrams from wojtekmaj which explains how the React lifecycle works.

Common lifecycles
All lifecycle

These two diagrams explain the flow of the lifecycle method. So let us see how to use them in our project.

Mounting

The mounting means to put elements into the DOM. React uses virtual DOM to put all the elements into the memory. It has four built-in methods to mount a component namely

  1. constructor()
  2. getDerivedStateFromProps()
  3. render()
  4. componentDidMount()

constructor()

constructor() method is called when the component is initiated and it’s the best place to initialize our state. The constructor method takes props as an argument and starts by calling super(props) before anything else.

Example

Here name is our initial state inside our constructor method and then we are calling our initial state to render method using this.state.name. The following code will output This is a Constructor Method .

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.

Example

In the above code, I have initialized some state in the constructor method inside our ChildComponent. After that, I have called that ChildComponent inside getDerivedStateFromPropsMethod which is the parent component and passed data (nameFromParent) from there to our ChildComponent. Now ChildComponent has nameFromParent props and now, we are changing our initial state of name inside the constructor method to props which we are receiving in getDerivedStateFromProps. The following code will output This is a getDerivedStateFromProps Method.

render()

This is the only compulsory method required by the React. This method is responsible to render our JSX to DOM

Example

componentDidMount()

The most common and widely used lifecycle method is componentDidMount. This method is called after the component is rendered. You can also use this method to call external data from the API.

Example 1

The above example will print This is a componentDidMount Method after 5 sec. This proves that the method is called after the component is rendered.

Example 2 Calling Data from API

In the above example, I have first initialized data as a blank array after that I have used the Javascript fetch method to load data from the API inside our componentDidMount method and then changed our data state using the React setState method from blank array to the data we are receiving from the API. Then we have used the javascript map function to iterate our data and print all users’ names from the API.

Updating

This is the second phase of the React lifecycle. A component is updated when there is a change in state and props React basically has five built-in methods that are called while updating the components.

  1. getDerivedStateFromProps()
  2. shouldComponentUpdate()
  3. render()
  4. getSnapshotBeforeUpdate()
  5. componentDidUpdate()

We have already discussed getDerivedStateFromProps() and render() a method so now let us discuss the remaining methods.

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.

Example

In the above example, you will notice that first I have initialized the name state inside the constructor method and after that changed state using setState inside componentDidMount method. So basically the name state should be changed from "shouldComponentUpdate Method" to “componentDidMount Method” after 5 seconds but it didn’t change because of shouldComponentUpdate set to false, If you change that true the state will be updated.

getSnapshotBeforeUpdate()

This method is called right before updating the DOM. It has access to props and state before the update. Here you can check what was the value of your props or state before its update. So let see how it works.

Note: componentDidUpdate() should be included otherwise you will get an error.

Example

In the above example, we initialized our name state as constructor Method after that changed that using setState in componentDidMount method to componentDidMount Method . So my previous state was constructor Method and the current state is componentDidMount Method So now I can get my previous State from the getSnapshotBeforeUpdate method. So using the getSnapshotBeforeUpdate method I have printed my previous state to our DOM using document.getElementById(‘previous-state’).innerHTML = “The previous state was “ + prevState.name.

componentDidUpdate()

The componentDidUpdate method is called after the component is updated in the DOM. This is the best place in updating the DOM in response to the change of props and state.

Example

In the above example, our initial name state was from previous state and after that using setState, I have set the name state to to current state So React will render the name state from State was changed from previous state to State was changed to current state after 5 seconds. Using the conditional checking of the current state with the previous state prevState.name !== this.state.name inside the componentDidUpdate method, we are updating the value of the id statechange to Yes the state is changed .

Note: You may also call setState inside componentDidUpdate but you must wrap that in a condition like in the example above or it’ll cause an infinite loop.

Unmounting

The final or the end of the react lifecycle is Unmounting. This is used when a component is removed from the DOM. React has only one built-in method that gets called when a component is unmounted

  1. componentWillUnmount()

componentWillUnmount()

If there are any cleanup actions like canceling API calls or clearing any caches in storage you can perform that in the componentWillUnmount method. You cannot use setState inside this method as the component will never be re-rendered.

Example

In the above example, I have created a simple toggle button which will show our Child component if the state is set to true. So after clicking on the button an alert will popup displaying This will unmount The alert will popup because the component is about to be removed from the DOM which in our case is the Child component.

Summary

  • The constructor() method is the best place to initialize our state
  • The getDerivedStateFromProps() is a rarely used lifecycle method and is the best place to set the state object based on the initial props.
  • The shouldComponentUpdate() specifies whether React should continue with the rendering or not.
  • The render() method is the most used and compulsory lifecycle method.
  • The getSnapshotBeforeUpdate() method has access to the props and state even after the update.
  • The componentDidMount() is the most common and widely used lifecycle method and is called after the component is rendered. You can also use this method to call external data from the API.
  • The componentDidUpdate() method is called after the component is updated in the DOM and is the best place in updating the DOM in response to the change of props and state.
  • The componentWillUnmount() happens just before the component unmounts and is destroyed and is used for cleanup actions like canceling API calls.

Below are the Github repository and live example for reference.

--

--

Manish Mandal
How To React

Full Stack Developer | React JS | Next JS | Node JS | Vue JS | Wordpress. Connect with me https://www.linkedin.com/in/manishmandal21/