ReactJS – componentDidMount Method

ReactJSWeb DevelopmentFront End Technology

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

This method is majorly used during the mounting phase of the React lifecycle to handle all the network requests or to set up all the major subscriptions of the application.

You can always set up network requests or subscriptions in the componentDidMount method but to avoid any performance issues, these requests are needed to be unsubscribed in the componentWillUnmount method which is called during the unmounting phase of the React lifecycle.

Syntax

componentDidMount()

Example

In this example, we will build a color-changing React application which changes the color of the text as soon as the component is loaded in the DOM tree.

Our first component in the following example is App. This component is the parent of the ChangeName component. We are creating ChangeName 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>
            <ChangeName />
         </div>
      );
   }
}
class ChangeName extends React.Component {
   constructor(props) {
      super(props);
      this.state = { color: 'lightgreen' };
   }
   componentDidMount() {
      // Changing the state after 3 sec
      setTimeout(() => {
         this.setState({ color: 'wheat' });
      }, 2000);
   }
   render() {
      console.log('ChangeName component is called');
      return (
         <div>
            <h1>Simply Easy Learning</h1>
         </div>
      );
   }
}
export default App;

Output

This will produce the following result.

raja
Updated on 18-Mar-2021 11:38:36

Advertisements