The componentDidMount() method allows us to execute the React code when the component is already placed in the DOM (Document Object Model). This method is called during the Mounting phase of the React Life-cycle i.e after the component is rendered.
All the AJAX requests and the DOM or state updation should be coded in the componentDidMount() method block. We can also set up all the major subscriptions here but to avoid any performance issues, always remember to unsubscribe them in the componentWillUnmount() method.
Creating React Application:
Step 1: Create a React application using the following command:
npx create-react-app functiondemo
Step 2: After creating your project folder i.e. functiondemo, move to it using the following command:
Project Structure: It will look like the following.
Example: In this example, we are going to build a name color application that changes the color of the text when the component is rendered in the DOM tree.
App.js: Now write down the following code in the App.js file. Here, App is our default component where we have written our code.
Step to Run Application: Run the application using the following command from the root directory of the project: