ReactJS – componentWillMount() Method


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

This method is used during the mounting phase of the React lifecycle. This function is generally called before the component gets loaded in the DOM tree. This method is called before the render() method is called, so it can be used to initialize the state but the constructor is preferred.

This method is generally used in server-side rendering. Don’t call subscriptions or side-effects in this method; use componentDidMount instead.

Note: This method is now deprecated.

Syntax

UNSAFE_componentWillMount()

Example

In this example, we will build a color-changing React application that 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' };
   }
   UNSAFE_componentWillMount() {
      // Changing the state immediately.
      this.setState({ color: 'wheat' });
   }
   render() {
      return (
         <div>
            <h1 style={{ color: this.state.color }}>Simply Easy Learning</h1>
         </div>
      );
   }
}
export default App;

Output

This will produce the following result.

Updated on: 18-Mar-2021

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements