ReactJS – componentDidUpdate() Method


In this article, we are going to see how to execute a function when the component is updated in the DOM tree.

This method is called only when the component gets updated or when the props passed to it change. It isn’t called for the initial render of the component. This method is majorly used to perform some operations which are needed to be executed only if the DOM is updated.

To avoid any performance issues, it is advised to use this method with conditional loop like −

componentDidUpdate(prevProps, prevState) {
   if (prevState.text !== this.state.text) {
      // Write logic here.
   }
}

Syntax

componentDidUpdate(prevProps, prevState, snapshot)

Parameters

  • prevProps - Previous props passed into the component

  • prevState   - Previous state of the component

  • snapshot   - Value returned by getSnapshotBeforeUpdate() method

Example

In this example, we will build a color-changing React application which changes the color of the text on the click of the button which will update the component and the componentDidUpdate method will be called.

Our first component in the following example is App. This component is the parent of the Change component. We are creating Change separately and just adding it inside the JSX tree in our App component. Hence, only the App component needs to be exported.

App.jsx

import React from 'react';
class App extends React.Component {
   render() {
      return (
         <div>
            <h1>Tutorialspoint</h1>
            <Change />
         </div>
      );
   }
}
class Change extends React.Component {
   constructor(props) {
      super(props);
      this.state = { color: '#000' };
   }
   componentDidUpdate() {
      console.log('componentDidUpdate method is called');
   }
   render() {
      return (
         <div>
            <h1 style={{ color: this.state.color }}>Simply Easy Learning</h1>
            <button onClick={() => this.setState({ color: '#0f0' })}>
               Change Color
            </button>
         </div>
      );
   }
}
export default App;

Output

This will produce the following result.

Updated on: 18-Mar-2021

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements