componentDidUpdate() | The Old Props and the New

After learning about React’s component lifecycle methods, it was clear to see the benefit and use-cases for a few of them. ComponentDidMount and render (naturally) were immediately put into practice within my projects. However, understanding the specific uses of the remainder of these methods seemed abstract. Therefore, I decided to dig deeper into one of these methods: componentDidUpdate().

Before I could explore specific examples for this method, I first needed to understand the basics.

When is it called?

After a render, specifically when a component gets updated. This occurs in two instances:

  • New Props have been provided by a parent component

To show this timing, let’s say there is a console.log located in the constructor, render, componentDidMount, and componentDidUpdate. If you setState on a button click below, the logs will read as follows:

Syntax

You can only call this method inside of a class component. This is true for all lifecycle methods. The function is written as follows:

componentDidUpdate(prevState, prevProps) {  
//prevState represents previous state
//prevProps represent the previous props
//to access the updated state and props, use
//this.props
//this.state
}

When to use it?

For this blog post, I will be focusing on one unique use case of the method.

Fetching Data that Changes Props

Oftentimes, a parent may be sending a prop down to its child that relates to its state. In this example, the parent will be passing down a player selected for a game.

A user can select a player from the screen by clicking a button that is rendered by the parent.

It is important to note that the child component receives the state of the parent as a prop. This presents on the screen as such:

Each of those buttons, when clicked, cause a state change in the parent component.

Let’s say the api is structured as such:

When a player selects Yoda or Kylo, we want to conditionally render their abilities at the bottom of the screen. There are a few key pieces to get this to load:

  1. Create state to accept an array of abilities

2. Be setup to render the abilities for the player passed in via the parent’s state:

3. Use componentDidUpdate to recognize the player prop changing on the bottom click and conditionally pass that player to a function that can set the state according to the api.

And there we have it! Since we check whether a player’s name has changed by comparing the old props to the new, we can request information when a change occurs.