componentDidUpdate() in ReactJS

componentDidUpdate(prevProps, prevState, snapshot) method is called when component is updated to DOM.

componentDidUpdate(prevProps, prevState, snapshot) will not be invoked when component is mounted to DOM for first time. It will invoked in Updating phase of component.

Why componentDidUpdate() should be used?

componentDidUpdate() can be used to re-render some third party libraries and to make some request to server if there is any change in props or state object.

class NumberComp extends React.Component{
  componentDidUpdate(prevProps, prevState){
      if(this.props.someValue !== prevProps.someValue){
            /* Do something */

As per above example, after comparing someValue of props, you can re-render third party libraries or make some request to server.

Points to remember while using componentDidUpdate()

There are many points that you should remember while using componentDidUpdate() method.

  • If getSnapshotBeforeUpdate() lifecycle method is used and returned some value, then componentDidUpdate(prevProps, prevState, snapshot) will have third parameter ( snapshot ) returned by getSnapshotBeforeUpdate() lifecycle method otherwise it will be undefined.
  • If you are doing some side effects work in componentDidUpdate() method, add some condition first otherwise it can create some performance issue.
  • If you are calling setState() method in componentDidUpdate(), you must add some comparision otherwise it will go into infinite loop. ( componentDidUpdate -> setState -> render -> componentDidUpdate -> setState -> render -> ..... )


In this section, we learned about componentDidUpdate() method and for what it can be used.
In the next section, you will learn about componentWillUnmount() method of ReactJS component.