Saturday, December 28, 2024
Google search engine
HomeLanguagesWhat is ComponentWillMount() method in ReactJS ?

What is ComponentWillMount() method in ReactJS ?

ReactJS requires several components to represent a unit of logic for specific functionality. The componentWillMount lifecycle hook is an ideal choice when it comes to updating business logic, app configuration updates, and API calls. 

The componentWillMount() lifecycle hook is primarily used to implement server-side logic before the actual rendering happens, such as making an API call to the server. The componentWillMount() method allows us to execute the React code synchronously when the component gets loaded or mounted in the DOM (Document Object Model). This method is called during the mounting phase of the React Life-cycle.

ComponentWillMount() is generally used to show a loader when the component is being loaded or when the data from the server is being fetched.

Features:

  • It allows us to modify the contents before displaying them to the end-user, which creates a better impression to the end-user, otherwise, anything can be displayed to the end-user.
  • Because it is a react system-defined method, if we want to achieve the same functionality with the help of writing any custom function then it will not be able to give us the same performance as it is part of the React lifecycle, and hence it is optimized.

Syntax:

  • Before performing any activity the first thing they will call is the constructor and then call for the componentWillMount() function.
  • Inside this function, we can perform some of the important activities like modification of HTML view for the end-users, etc.
  • The next thing will be called to render, as we have already done some modification in the componentWillMount() section the changed value will be displayed at the user end.

Javascript




componentWillMount() {
    // Perform the required
    // activity inside it
}
 
// Call the render method to
// display the HTML contents.
render(){
}


Creating a react app:

Step 1: Run the below command to create a new project

npx create-react-app my-app

Step 2: The above command will create the app and you can run it by using the below command and you can view your app in your browser.

cd my-app
npm start

Project Structure: It will look like the following

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.

ComponentWillMount to manipulate State(): The life-cycle hook componentWillMount() triggers before the initial render, and the function will only trigger once in the lifespan of a component. Once the component gets initiated, the current state value will be overridden with the updated value, but keep in mind this happens once in a lifetime of a component. And the last step is to print the message inside the render() function, as demonstrated below.

Javascript




import React, { Component } from "react";
 
 
class App extends Component {
    constructor() {
        super();
        this.state = {
            message: "This is initial message"
        };
    }
 
    componentWillMount() {
        this.state = {
            message: "This is an updated message"
        };
    }
 
    render() {
        return (
            <div>
                <h2>Update the state</h2>
                <h3>  {this.state.message} </h3>
 
            </div>
        );
    }
};
 
export default App;


Explanation: When we run the above example, the message variable’s value is updated once the component gets initiated; this is the standard way to manipulate the business logic.

Output:

ComponentWillMount() to Make API Calls: componentWillMount() is to make API calls once the component is initiated and configure the values into the state. To make an API call, use an HttpClient such as Axios, or we can use fetch() to trigger the AJAX call.  The function with the fetch() API call is shown below. fetch() is used along with the dummy API URL, which hits the server and fetches the data; in the end, the response is updated into the state variable todo, which contains the object. After getting the response from the API, we can consume the data as per requirements. Below is a complete example of this

dummy API URL: https://jsonplaceholder.typicode.com/todos/3

Javascript




import React, { Component } from "react";
 
class ApiCall extends Component {
    constructor() {
        super();
        this.state = {
            todo: {}
        };
    }
 
    componentWillMount() {
            .then(response => response.json())
            .then(json => {
                this.setState({ todo: json });
            });
    }
 
    render() {
        const { todo } = this.state;
        console.log(todo)
        return (
            <div>
 
                <p>API call :</p>
 
 
                Todo title :
                <p>{todo.title}</p>
 
 
                Todo completed :
 
                <p>{todo.completed === true ? "true" :
                    "false"}</p>
 
            </div>
        );
    }
}
 
export default ApiCall;


Output:

Note: Changing the state value inside componentWillMount will not re-run the component again and again, unlike other life-cycle methods.

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments