DEV Community

Cover image for How to use React Lifecycle Methods
Andreas Reiterer
Andreas Reiterer

Posted on • Originally published at andreasreiterer.at on

How to use React Lifecycle Methods

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 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. 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()
Enter fullscreen mode Exit fullscreen mode

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. 

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 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)

componentDidMount

componentDidMount()
Enter fullscreen mode Exit fullscreen mode

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  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)
Enter fullscreen mode Exit fullscreen mode

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 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)
Enter fullscreen mode Exit fullscreen mode

By default, this method is not implemented, so 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 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 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:  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)
Enter fullscreen mode Exit fullscreen mode

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:

componentDidUpdate

componentDidUpdate(prevProps, prevState)
Enter fullscreen mode Exit fullscreen mode

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()
Enter fullscreen mode Exit fullscreen mode

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, or send an email to 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, 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 appeared first on my blog.

Top comments (7)

Collapse
 
ben profile image
Ben Halpern

Andreas, mods had to remove the newsletter CTA because the embed wasn't compatible with our markdown. Feel free to add a link back in.

Collapse
 
a_reiterer profile image
Andreas Reiterer

Hey Ben,
just before I add it again in a wrong way - what exactly did not work?
In the version of the article that I published, the CTA was only a paragraph of text with two links.
Did I embed something?
However, thanks for notifying me, since this is my first post here, chances are that I just did something wrong 🙃

Collapse
 
a_reiterer profile image
Andreas Reiterer

Hah ... I just realized what's going on, this is a different article.
So everything is fine now thanks :)

Collapse
 
waize profile image
Paul Reicherzer

Hey Adreas,
I'm using your post here as main reference for getting back the meaning of every state. I like this much more than the official docs from react! :)

Since v 16.3 there are new lifecycle methods. Is there any chance that you update this post here or have an updated version somewhere?
I will appreciate it very much!

Collapse
 
a_reiterer profile image
Andreas Reiterer

Hello Paul!

Thank you, I'm happy that my cheatsheet helps you :)
And thank you for reminding me that this post is outdated.
When 16.3 came out, I updated the original version but never updated the one on DEV.to

Collapse
 
siuhangw profile image
Wong Siu Hang

Very clear explanation. Thank you

Collapse
 
jreina profile image
Johnny Reina

Excellent write up! Bookmarking this.