Software systems to innovate and grow

Understand React Lifecycle Methods

By Engineering Team July 15, 2019 10 mins read

From inception to destruction, React components go through a lifecycle. This lifecycle marks the stages of mounting, updating, unmounting and error handling of your component. Each stage exposes a few member functions (or methods) developers can override to empower the component to React to the changes the component undergoes.

It is not necessary for all the lifecycle methods to be executed during each component’s life. The component could just be rendered and immediately deleted without anything else happening in between, hence how the update and error handling stage may be skipped.

The lifecycle methods have received a few updates in the past, therefore there are some deprecated methods, which will soon be phased out of the stable releases. We will not discuss these methods but will talk about all the methods currently available, including the less common ones.

The official React documentation has a good component lifecycle diagram, which will give you a top-down view of the execution of all the methods.

Let’s begin by taking a look at the mounting phase, which occurs when the component is created for the first time.

Mounting Phase

The mounting or birth of your component defines the stage where your component is created and rendered on the DOM. It encapsulates the following methods:

constructor()

The constructor is the first method executed and is called before mounting. This method is typically used for two reasons, binding member functions and setting the initial state. Each can only be used in class components.

If you do make use of a constructor, make sure to call super() with the props as an argument, otherwise ‘props’ will be undefined in the component.

Since we need to initialize state, this is the only place where we can directly define state without using setState(). You should also not use setState() in the constructor anyway, to avoid unexpected behavior. If you’re using arrow functions in your component, then you don’t need to bind ‘this’ to the functions as it is already implicitly passed.

static getDerivedStateFromProps()

This method is a new addition, and also one of the less commonly used lifecycle methods. It is the last to execute before the component is rendered, and is executed every time the component updates, including the initial render.

It is usually used to set the initial state depending on the props passed to the component. Its return value has to be either null or an object that updates the state.

render()

The render method is the only required method in a component. It is responsible for rendering the JSX into the DOM. If using conditional rendering, some simple logic can be applied inside this method, such as a ternary operator or pure functions.

It is not a good idea to update the state inside the render method, as this induces an infinite render() loop and is called every time the state changes.

componentDidMount()

When your component is loaded in the DOM, this method is executed. Therefore, it makes this an ideal place to perform any API calls or make changes to the DOM. After executing once, it is not triggered again for the duration of the component’s life.

You can use setState() here to modify the state, which is commonly done when data is fetched from a network request. However, if you need to set the state immediately and you don’t need to access the DOM, it is always a better idea to do that in the constructor.

That’s it for the mounting phase, now we’ll look at what happens when the component is updated.

Update Phase

The modification phase can be triggered using three methods:

  1. Receiving new props
  2. Calling setState() and updating the state
  3. Using this.forceUpdate

It doesn’t matter which way is used to update the component; it will always trigger the same methods. getDerivedStateFromProps() and render() methods discussed earlier are executed in this phase as well.

shouldComponentUpdate()

This method is designed to increase performance in React applications. It accepts the previous state and previous props, which you can compare with the current state and props and using a conditional operator, return true or false depending on whether React should update the component or not.

getSnapshotBeforeUpdate()

This is a new method recently introduced in React. It can be used as an alternative for the now deprecated componentWillUpdate(). As there may be a delay between the time when the changes are committed and when they are reflected in the DOM, this method allows us to capture the condition or state of our application just before the DOM is updated.

getSnapshotBeforeUpdate() can be very helpful when we need to use the previous state of the DOM to make changes to the component after it has updated. For example, we can get the current Y position of our page, and compare it with the updated Y position to determine if we need to scroll down or not.

This method either returns null, or as a value which can be accessed in the next method, componentDidUpdate().

componentDidUpdate()

This method is executed right after all the changes have been propagated to the DOM. Here, we have access to the previous props, state and the value returned by getSnapshotBeforeUpdate() also known as the snapshot.

If we want to modify the state in this method, we must do so in a conditional statement. Otherwise, it may fall into an infinite loop as the state is updated, and then this method is called again which updates the state, and so on.

Unmount Phase

This phase contains one very important method, componentWillUnmount().

componentWillUnmount()

This method is called right before the component is unmounted from the DOM. Here, you can call any last-minute actions or perform any clean-up required. You’ll need to make sure to clean up any subscriptions or events in componentWillUnmount(), that you may have created earlier in componentDidMount.

Error Handling

The error handling phase is not a default part of the component lifecycle, rather it can be used to empower the component to catch any errors in the child tree, and log the errors and/or display a fallback UI.

It provides two methods used to manage errors:

static getDerivedStateFromError()

When an error occurs, this method receives the error object. You can update the state, depending on the error, to be used anywhere in the component, possibly to show a fallback UI.

Note that you don’t execute any side effects in this method, as it is used only to return the updated state or null value.

componentDidCatch()

Similar to the above method, this is called when an error occurs in the child tree. It accepts an error as a parameter, and here you are able to perform any side effects like logging the error and so on.

In a common scenario, you would typically create an error boundary component and wrap your parent component with it. An error boundary component is just a normal component, except that it includes one or more of the above-mentioned error handling methods, which can be used exclusively for error handling.

The official React documentation provides a concise way of creating an error boundary component to wrap your components in.

Wrapping your component inside ensures that if any error occurs, the text under the h1 heading “Something went wrong.” Will be displayed instead of nasty looking error messages that the end-user would not want to see.

Understanding Lifecycle Methods

These are all the lifecycle methods available in the latest stable build of React. Understanding when to use them and how to use them is one of the core concepts of React that every developer should know if they want to sharpen up on their skills. They also happen to be good things to know for interview questions, so make sure to put them in use next time you’re working with components in React.