Quickly Understand React's componentDidUpdate() API

Quickly Understand React's componentDidUpdate() API

In this scenario, we explore how componentDidUpdate() can be used to fire a secondary API call after we receive data from a primary API call.

Imagine we had an app where an initial page load calls an API that fetches a single YouTube video.

Our React app then updates state to hold both the video object we received in the response body, and also stores the video's videoId string in a second piece of state.

We receive our video videoId data from our first API call. But now we must make a subsequent API request only after we received our videoId, so that we may retrieve comments from a different API with that videoId parameter.

class App extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      video: {},
      videoId: '',
      videoComments: []
    };
  }

... 

}

It's critical to understand that any logic within componentDidUpdate() needs to be conditional, and leverages three automatically given arguments - prevProps, prevState and snapshot.

In this short article, we'll focus on prevState.

  1. After we update App's state with video and videoId, a re-render is triggered.
  2. Because componentDidUpdate only runs after our first component render, we now run the following logic within the below method call:
  3. Because we can now conditionally compare our previous state to our current state, we know whether or not to run our next API call to comments API, given that our videoId state has now successfully changed.
class App extends React.Component {
// Our previous state is updated above
...

componentDidUpdate(prevProps, prevState, snapshot) {
   if (this.state.videoId !== prevState.videoId) {
     // make call to comments API now that we have updated videoId
   }
}

}

componentDidUpdate is automatically given our previous props, state, and what is called a snapshot.

That's it! We now successfully made two asynchronous API calls, where our second API call (comments) required logic from our first API call (video data, including videoId).

For more reading on this, I recommend React's excellent documentation on React's component classes.