Notebook and monitor with a clock on it

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() / static getDerivedStateFromProps()
  • render()
  • componentDidMount()

Update: componentWillMount will be marked deprecated in a future React 16.x release and will be removed with React 17. With React 16.3 there were new lifecycle methods introduced.

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() / static getDerivedStateFromProps()
  • shouldComponentUpdate()
  • componentWillUpdate() / getSnapshotBeforeUpdate()
  • render()
  • componentDidUpdate()

Update: componentWillReceiveProps and componentWillUpdate will be marked deprecated in a future React 16.x release and will be removed with React 17. With React 16.3 there were new lifecycle methods introduced.

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
  • static getDerivedStateFromProps()
  • componentDidMount
  • componentWillReceiveProps
  • shouldComponentUpdate
  • componentWillUpdate
  • getSnapshotBeforeUpdate()
  • 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.

Update: componentWillMount, componentWillReceiveProps and componentWillUpdate will be marked deprecated in a future React 16.x release and will be removed with React 17. With React 16.3 there were new lifecycle methods introduced.

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

Whenever React renders a component, it’s going to call componentWillMount 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.

Update: componentWillMount is considered legacy and you should avoid it in new code.

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

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)

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.

Update: componentWillReceiveProps is considered legacy and you should avoid it in new code.

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)

static getDerivedStateFromProps

static getDerivedStateFromProps(props, state)

This method is called on every render – even if props didn’t change. So be careful when you’re using this method – it only exists for very rare use cases where the state depends on changes in props. Be sure if you really need this method.

Use Cases

There are some rare use cases where you might need to derive state from props, like when you’re implementing a <Transition>component that compares it’s previous and next children to decide which ones it should animate in and out.

shouldComponentUpdate

shouldComponentUpdate(nextProps, nextState)

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)

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.

Update: componentWillUpdate is considered legacy and you should avoid it in new code.

State

You can’t call setState here. Again, if you want to set the state because of changing props, use componentWillReceiveProps getDerivedStateFromProps 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:

getSnapshotBeforeUpdate

getSnapshotBeforeUpdate(prevProps, prevState)

This method was added with React 16.3 and in combination with componentDidUpdate it should cover all use cases for the legacy method componentWillUpdate.

getSnapshotBeforeUpdate is called right before the rendered elements are written to the DOM. This way you can capture information from the DOM (e.g. scroll position) before it will be updated.

You should return a snapshot value or null. Whatever you return, will be available as snapshot argument of componentDidUpdate()

Use Cases

If you want to get the scroll position of a list or in a chat window, you would retrieve this information in this method. Then you would return the scroll position as snapshot value. This allows you to set the correct scroll position after the DOM was updated, in componentDidUpdate

componentDidUpdate

componentDidUpdate(prevProps, prevState, snapshot)

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.

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.

If you want to read more about React’s component lifecycle, I’d recommend to have a look at the official documentation

A good thing to note here is, that you can only use life cycle methods, when you’re using class components, since functional components don’t support life cycle methods. Read more about it here:

React Functional Components vs. Class Components

Improve your React Skills!

Learn about React concepts, helpful libraries or get tips & tricks for deploying your app and many more topics.

I semi regularly post about React. Don't miss out on my future posts! Sign up below to get them delivered directly into your inbox!

5 thoughts on “How to use React Lifecycle Methods”

    1. Thanks! That’s true, most of my components are functional components too. But especially for API calls and initialisation you don’t get around lifecycle methods 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *