How can we implement componentDidUpdate to check for any changes in props or state?

Question

In the context of this exercise, how can we implement componentDidUpdate to check for any changes in props or state?

Answer

There are a few ways that this method can be implemented, with two common implementations as follows:

One way is to check if there has been any change to the props or state at all, using a condition like the following,

componentDidUpdate(prevProps, prevState) {
  if ((this.props !== prevProps) || (this.state !== prevState)) {
    // code
  }
}

Or, you might check if specific values have changed only, like follows,

componentDidUpdate(prevProps, prevState) {
  if (this.props.specificValue !== nextProps.specificValue) {
    // code
  }
}
3 Likes

hey,

i assume there is a typo in the second example but let me correct me if not:

componentDidUpdate(prevProps, prevState) {
if (this.props.specificValue !== nextProps.specificValue) {
// code
}
}

instead of nextProps we should use prevProps

please update, thanks.

7 Likes