How to use React Lifecycle Methods » Andreas Reiterer

  • React components have several “lifecycle methods” that allow us to execute actions (e.g.: fetching data from a server) at particular times.
  • When React creates an instance of a component and inserts it into the DOM (mounting), the following methods are called:

    If props or state of a component are changed for whatever reason, an update of the component is performed.

  • That process is called unmounting and means that the following method is called:

    I hope I could give you a short overview of the life of a React component and the calling order of lifecycle methods.

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

    Whenever this method is called, React has already rendered our component and put it into the DOM.

  • This means, it could be possible that the method returns false but React still decides to re-render the component.

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

@a_reiterer: New Post: How to use React Lifecycle Methods. Enjoy the read 🙃
#webdev #reactjs #React #javascript

React lifecycle methods can be confusing if you don’t know which one to use for your particular use case. Basically, the lifecycle of a React component consists of three stages: Mount, Update and Unmount. Each of them calls certain lifecycle methods, that you can use for certain actions. For example, when initially mounting a component, you can use componentDidMount to fetch the data you want to show from a server. 

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: Mounting, updating and unmounting the instance of a component.

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

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:

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:

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.

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.

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.

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.

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

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.

You can set the state by using this.setState()

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

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.

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.

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

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)

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.

You can use setState here.

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.

You can’t set state before unmounting the component.

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

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 don’t want to miss out and get all my new articles delivered right to your inbox on a weekly basis, I have good news for you: I just started a newsletter and I would be happy to count you to my subscribers.

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.

How to use React Lifecycle Methods » Andreas Reiterer