The Lifecycle of a React Component

Karina Guerra
CodeX
Published in
6 min readJan 5, 2021
Let's talk about the React component circle of life!

In React applications, we use components to split and isolate different parts of the web user interface into individual pieces. These pieces act independently and use a render function to return React elements in JSX. These elements describe how that section should be displayed to the user.

Each component goes through three phases: mounting, updating and unmounting. You can also think of it as our natural life cycle: we are born, we grow (adolescence and adulthood), and eventually, we die. React components are created by being mounted onto the DOM, they change or grow through updates, and finally, they can be removed or unmounted from the DOM. These three milestones are referred to as the React component lifecycle.

(Note: A React Component may or may not go through all phases. Sometimes they are never updated. Other times they are never unmounted. A component can even go through the mounting phase and unmounting phase back to back without ever updating.)

A modern diagram of React Lifecycle
Modern diagram for the React component lifecycle.

The diagram above shows the overall modern lifecycle of React components with their appropriate lifecycle methods. React provides specific lifecycle methods that can be used to perform specific actions in different phases. These are called React component lifecycle methods. Let’s take a closer look!

Mounting Phase

This phase refers to the component’s creation. This is where the component is added to the DOM.

These are the lifecycle methods available for this phase:

constructor()

Before the start of the mounting phase, we may need to initialize our component using a constructor() method. This is used when we need to initialize state and bind methods to our component. This is the only place wherethis.state is explicitly assigned. (Do not use setState here.)

Again, two important things happen in this step:

  1. An object is assigned to this.state
  2. Methods are passed/bound to the instance of the class through props

static getDerivedStateFromProps()

After initializing, the next function that is invoked is static getDerivedStateFromProps(). This method is invoked before the render function of the component (and before the initial mount).

This method allows a component to update its states based on changes to its props. It is rarely used and should be used with caution as it can cause errors. The general rule as a beginner, you probably don’t need it and should avoid using it.

render()

The render() method is the only method that the component is required to have. It will always be called and its job is to mount the component to the DOM. The render() method can return any of the following:

  • React Elements: Written in JSX, these are the plain object that describes what we want the user to see
  • Arrays or Fragments: These allow you to return multiple React elements. Arrays are declared using [], and fragments can be declared by using empty tags <> </>
  • Portals: These allow you to render children into different DOM subtrees (outside of the DOM hierarchy)
  • Booleans or null: Essentially this renders nothing but can be used for conditional situations
  • Plain numbers and strings

The React documentation describes the render function as “pure”. This means that anything returned in the function should not change the component’s state. (Never use setState or make network requests here.)

componentDidMount()

The last function in this phase is componentDidMount(). This method will be immediately invoked after the render function is executed. If we need to interact with the browser directly, this is where we do it. We can make an API call and update the components state based on its response. We can fill in the content from data we load from another endpoint. Calling setState() should be used here as it will call the render function again and handle asynchronous processes like fetch requests.

Recap of the Mounting phase lifecycle methods.

Updating

This second phase represents times where a component needs to update due to a change in its props or state. These changes can occur within the component or through the backend. These changes will trigger the render function again.

Here are the lifecycle methods:

static getDeprivedStateFromProps() (Again)

This is the first method to be invoked in this phase. This method is the same method used in the mounting phase.

shouldComponentUpdate()

The next method to be invoked is the shouldComponentUpdate() method. As the name suggests, this method gives you control over whether or not a component should update due to a change in its props or state. By default, a component will always re-render when updated. This method can either return a true or false. Also, this method receives nextProps and nextState as arguments so you can always compare it with the component’s current prop and state values. This method can help with performance optimization but it is also rarely used.

render()

If shouldComponentUpdate() returns true, the render function is invoked immediately.

getSnapshotBeforeUpdate()

In this method, we are given access to the props and state value before the update is committed to the DOM. Even though the render function was already called, we are still able to see the previous values. The use of this case is uncommon but can be used to capture any information we may need. It is important to note that this method works for hand in hand with componentDidUpdate(), which is the next lifecycle method that we will discuss.

componentDidUpdate()

This method is the last one invoked in this phase. Like the previous method, it also receives the former props and state values as arguments but it also receives the return value getSnapshotBeforeUpdate() as a third argument (if present).

It is typically used to make more fetch requests on the condition of comparing the current and previous props and state values. Therefore, you may call setState but within a conditional statement.

Recap of the Updating phase lifecycle methods.

Unmounting

Finally, the unmounting phase is where the component is removed from the DOM. This marks the end of a component's lifecycle. In this phase, we have one lifecycle method available to us:

componentWillUnmount()

This method is executed right before the component is unmounted from the DOM. You can think of this method as a way to clean up anything that is needed to be removed before the component is destroyed.

BONUS: Error Handling

In addition to these lifecycle methods, some methods are invoked when an error occurs during rendering. React 16 introduced the concept of “error boundary” which are simply React components that catch JS errors. They will catch these errors, log them, and then display a “fallback” UI. This is useful because one JS error will not break the whole app for the user.

The way we implement this concept is by creating a new class component (usually called ErrorBoundary). We wrap the component around a child component. You should only create this class once and reuse it in different parts of your React application.

There two methods associated:

static getDerivedStateFromError()

If an error were to occur in the child component, this method is invoked. The error will be passed as an argument and this method would return a value that will update the state of the class component. This method is useful for rendering a custom fallback UI instead of rendering a broken component.

componentDidCatch()

This method receives the error as an argument as well as an object that has information about the error. This method is perfect for logging the error!

Example directly from the React Docs.

--

--

Karina Guerra
CodeX
Writer for

Salvadoreña exploring the world of coding. Petting animals and building things that help people and the environment are my two biggest passions :) Based in NYC.