VOOZH about

URL: https://www.geeksforgeeks.org/reactjs/reactjs-unsafe_componentwillmount-method/

⇱ ReactJS UNSAFE_componentWillMount() Method - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

ReactJS UNSAFE_componentWillMount() Method

Last Updated : 27 Jul, 2025

The invokes right before our React component gets loaded or mounted in the (Document Object Model). It is called during the mounting phase of the , i.e., before . It is used to fetch data from outside the component by executing the React code synchronously which causes our component to render with empty data at first because this method doesn't return anything before our component renders for the first time. As the fetch calls are asynchronous, our component doesn't wait for this method to finish and continues to get rendered.

The componentWillMount() method has been deprecated in the latest releases of React as per this . It is recommended to use in its place but if we still want to use componentWillMount() we can do it by calling it as UNSAFE_componentWillMount(). It's not suggested using this method according to React, that's why the UNSAFE keyword comes at the beginning to give a gentle message to all the React developers to stop using this method. This method can be used to perform an action just before our React component gets mounted in the DOM.

Syntax:

class App extends Component {

 UNSAFE_componentWillMount() {
 
 //action you want to execute
 
 }
}

Creating React Application:

Step 1: Create a using the following command.

npx create-react-app foldername

Step 2: After creating your project folder i.e. foldername, move to it using the following command.

cd foldername

Project Structure: It will look like the following.

👁 Image

Example: In this example, we are going to build an application that gives an alert message before our React component loads in the DOM. Now write down the following code in the App.js file. Here, App is our default component where we have written our code.

Filename: App.js

Step to Run Application: Run the application using the following command from the root directory of the project.

npm start

Output: Now open your browser and go to http://localhost:3000/, you will see the following output.

👁 Image

Explanation: We receive an alert message through UNSAFE_componentWillMount() method before our component gets mounted in the DOM and then our component loads after rendering. This way, we can perform any action just before our component loads. As you can see a warning message also appears at the console when our component loads which clearly tells us that this method is not recommended for the use which we already discussed above.

Comment