How to use React Lifecycle Methods
Tags: webdev, react, javascript
Published: 2017-09-21 23:28:41

---
title: "How to use React Lifecycle Methods"
description: Use React lifecycle methods to perform actions on mount, update and unmount of a component. Learn more about e.g. componentDidMount and when to use it
published: true
tags: webdev,react,JavaScript,
canonical_url: http://www.andreasreiterer.at/web-development/reactjs-lifecycle-methods/
cover_image: http://www.andreasreiterer.at/wp-content/uploads/2017/09/markus-spiske-377956-825x510.jpg
---

_React lifecycle methods can be confusing if you don’t know which one to use for your particular use case. Today I’m going to show you, which lifecycle methods exist, and how to use them correctly._

## Introduction

React components have several “lifecycle methods” that allow us to execute actions (e.g.: fetching data from a server) at particular times. When I started learning React, I found it hard to figure out which lifecycle method i should use for certain actions. If this is the case with you too, this article should serve as a handy guide.

I will start with an overview of all lifecycle methods and explain in which order they are called. Then I’ll handle each of them with a short explanation and some example use cases. In the end, you should have a better understanding of when to use which life cycle method.

## The Lifecycle of a React Component

Let’s begin with the lifecycle of a component according to the React docs. There are three particular stages in the lifecycle of a component, that are important for our lifecycle methods, which I will explain:

- Mount
- Update
- Unmount

### Mount

When React creates an instance of a component and inserts it into the DOM (_mounting_), the following methods are called:

- _constructor()_
- _componentWillMount()_
- _render()_
- _componentDidMount()_

### Update

If props or state of a component are changed for whatever reason, an update of the component is performed. However, this means that the component has to be re-rendered, which causes the following methods to be called:

- _componentWillReceiveProps()_
- _shouldComponentUpdate()_
- _componentWillUpdate()_
- _render()_
- _componentDidUpdate()_

### Unmount

At some point our components will be removed from the DOM again. That process is called _unmounting_&nbsp;and means that the following method is called:

- _componentWillUnmount_

### React Component Lifecycle Summary

I hope I could give you a short overview of the life of a React component and the calling order of lifecycle methods. Just for a compact overview, here’s a list of all lifecycle methods in the correct order.

- _componentWillMount_
- _componentDidMount_
- _componentWillReceiveProps_
- _shouldComponentUpdate_
- _componentWillUpdate_
- _componentDidUpdate_
- _componentWillUnmount_

You can see, they’re not that many. However, it is important that you choose the right one for different use cases to prevent side effects or errors.

## Lifecycle Methods

In this section, we are going to explore the different lifecycle methods.&nbsp;I will explain each of them in detail and I’ll do my best to provide different example use cases for a better understanding.

### componentWillMount()

```
componentWillMount()
```

Whenever React renders a component, it’s going to call c_omponentWillMount_ first. Note that this method is only called once in a life of a component, and this is right before it is initially. Therefore, there is **no access to the DOM.&nbsp;**

**Note:** Because componentWillMount is called before the _render()_ method, this is the only lifecycle method that is called on the server side, when you use serverside rendering.

Alternatively to this lifecycle hook, the React docs recommend using the constructor instead.

#### State

You can use _this.setState(…)_ inside this method. However, be aware that it [**may not trigger a re-rendering**](https://facebook.github.io/react/docs/react-component.html#componentwillmount) when you set the state **synchronously**.

If you can, I would suggest to set the default state inside the constructor instead of setting the state here.

#### Use cases

I did not find much example use cases for componentWillMount. Some people suggest to use it for doing some configuration of the root component that you can only do at runtime (e.g.: [setting up a Firebase connection](https://engineering.musefind.com/react-lifecycle-methods-how-and-when-to-use-them-2111a1b692b1))

### componentDidMount

```
componentDidMount()
```

Whenever this method is called, React has already rendered our component and put it into the DOM. Therefore, if there is any initialization you want to perform that relies on the DOM, do it here and now.

#### State

You can set the state with _this.setState()_. Whenever you do this, it will also trigger a re-render of the component.

#### Use Cases

You can use componentDidMount to **fetch data from a server** with AJAX calls. Also if you need to&nbsp; **initialize anything that relies on the DOM,** you can do this here (e.g. initializing third party libraries like D3). And last but not least, you can **add event listeners** inside componentDidMount.

### componentWillReceiveProps

```
componentWillReceiveProps(nextProps)
```

Whenever a component receives a new set of props, this method will be called first. Also, please note, that React calls this method, even when the props have not changed. So whenever you use this method, be sure to compare _this.props_ to _nextProps_ to avoid setting the state unnecessarily.

React doesn’t call this method in the **mount** process. Instead, it only calls this method, if some of the component’s props may update.

#### State

You can set the state by using&nbsp;_this.setState()_

#### Use Cases

If you have a state that is a calculation from multiple props, you could do the calculation here. Don’t forget to check if your relevant props have really changed (compare _this.props_ to _nextProps_)

### shouldComponentUpdate

```
shouldComponentUpdate(nextState, nextProps)
```

By default, this method is not implemented, so&nbsp;every update of state or props causes a render, even if the props didn’t change. However, if you want to avoid possible unnecessary renders, you could handle this here. Returning&nbsp;_false_ means, that React will not execute _componentWillUpdate()_, _render()_ and _componentDidUpdate()_.

This method is not called for the initial render.

**Note:** According to the React docs, React may treat shouldComponentUpdate like a hint instead of strictly following it’s return value. This means, it could be possible that the method returns&nbsp;_false_ but React still decides to re-render the component.

#### State

You can’t call _setState_ here. Also, it wouldn’t make much sense to do so. If you want to set the state because of changing props, use _componentWillReceiveProps_ instead.

#### Use Case

As already mentioned, you can check, if the update of props or state really affects the output of the component. To do so, you could do a comparison of the current props/state to the next props/state. If the component shouldn’t update, just return false and the component won’t update.

**Note:&nbsp;** This might lead to serious side effects. React also provides another solution for this use case: If you notice that a certain component is slow, you can inherit it from _React.PureComponent_ instead of _React.Component_. It will perform a shallow comparison for props and state, which might work for most of the use cases I can imagine right now.

### componentWillUpdate

```
componentWillUpdate(nextProps, nextState)
```

This method is invoked right before rendering. Like _shouldComponentUpdate_, it is called whenever new props are passed to the component, or the state is changed.

This method is not called for the initial render.

#### State

You can’t call _setState_ here. Again, if you want to set the state because of changing props, use _componentWillReceiveProps_ instead.

#### Use Cases

You can perform preparations that need to be done before updating the component. This lifecycle method is called right before render(), so you should not do anything that relies on the DOM – it will soon be outdated.

Common use cases seem to be:

- set a variable based on state changes
- dispatching events
- [starting animations](https://stackoverflow.com/questions/33075063/what-is-the-exact-usage-of-componentwillupdate-in-reactjs/33075514#33075514)

### componentDidUpdate

```
componentDidUpdate(prevProps, prevState)
```

Yay! Everything went well, and React updated our component. Directly after rendering, React also calls _componentDidUpdate_.

This method is not called for the initial render.

#### State

You can use _setState_ here.

#### Use Cases

If there is something you have to do with the DOM right after the component has been updated, this is the time and place for it. A good example for this would be the update of a 3rd party UI library like D3 to pass on the new data.

It is also a good place to **perform network requests** , as long as you compare the current state/props with the previous state/props to avoid unnecessary network requests.

### componentWillUnmount

```
componentWillUnmount()
```

Right before React unmounts and destroys our component, it invokes _componentWillUnmount_.

#### State

You can’t set state before unmounting the component.

#### Use Cases

Use this hook to perform clean up actions. This could be

- removing event listeners you added in _componentDidMount_ (or elsewhere)
- cancelling active network requests
- invalidating timers
- cleaning up DOM elements that you created in _componentDidMount_

## Wrapping up

Today you’ve learned, that the lifecycle of a React component consists of three stages: Mounting, Updating and Unmounting.

Also you’ve learned that React calls a certain set of lifecycle methods at each of those stages. You can use them according to the use case you want to fulfill.

Thank you for reading this article. I really hope you enjoyed it. Also, I would really appreciate it if you share this article with your friends.

If there is something you want to add, or if you just want to chat about dev stuff, hook me up on [Twitter](https://www.twitter.com/a_reiterer), or send an email to [hi@andreasreiterer.at](mailto:hi@andreasreiterer.at).

# Call to Action

You also want to become a better developer? I'm sharing what I know on my blog, and if you subscribe to my [weekly newsletter](www.andreasreiterer.at/weekly-webdev-newsletter/), I will deliver more tips and tricks about React and other web development articles right into your inbox.

_The post [How to use React Lifecycle Methods](http://www.andreasreiterer.at/web-development/reactjs-lifecycle-methods/) appeared first on [my blog](http://www.andreasreiterer.at)._