Author avatar

Gaurav Singhal

How to Use componentWillMount in React

Gaurav Singhal

  • Jul 31, 2020
  • 4 Min read
  • 43,326 Views
  • Jul 31, 2020
  • 4 Min read
  • 43,326 Views
Web Development
Front End Web Development
Client-side Framework
React

Introduction

Working with a library like React requires several components to represent a unit of logic for specific functionality. Hence, it requires consuming resources. 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. In this guide, you will learn to use componentWillMount() and make API calls after the initial component rendering.

Using componentWillMount() to Manipulate State

As you know, the life-cycle hook componentWillMount triggers before the initial render, and the function will only trigger once in the lifespan of a component.

It is used to update the state value before the DOM is rendered, creating a state variable, as shown below.

1constructor() {
2    super();
3    this.state = {
4      message: "This is initial message"
5    };
6}
jsx

As shown above, there is one state variable called message with a default string. Now update the message as shown below.

1componentWillMount() {
2    this.setState({ message: "This is an updated message" });
3}
jsx

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.

1render() {
2    return (
3      <div>
4        <p>Update the state</p>
5        <hr />
6        {this.state.message}
7      </div>
8    );
9}
jsx

When you 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.

Using componentWillMount() to Make API Calls

One of the primary usages of 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 or you can use fetch() to trigger the AJAX call.

The function with the fetch() API call is shown below.

1componentWillMount() {
2    fetch("https://jsonplaceholder.typicode.com/todos/1")
3      .then(response => response.json())
4      .then(json => {
5        this.setState({ todo: json });
6      });
7}
jsx

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.

1this.setState({ todo: json });
jsx

After getting the response from the API, you can consume the data as per your requirements. Below is a complete example of this.

1import React, { Component } from "react";
2
3class ApiCall extends Component {
4  constructor() {
5    super();
6    this.state = {
7      todo: {}
8    };
9  }
10
11  componentWillMount() {
12    fetch("https://jsonplaceholder.typicode.com/todos/1")
13      .then(response => response.json())
14      .then(json => {
15        this.setState({ todo: json });
16      });
17  }
18
19  render() {
20    const { todo } = this.state;
21    console.log(todo)
22    return (
23      <div>
24        <p>API call :</p>
25        Todo title : <p>{todo.title}</p>
26        Todo completed : <p>{todo.completed === true ? "true" : "false"}</p>
27      </div>
28    );
29  }
30}
31
32export default ApiCall;
jsx

Keep in mind that changing the state value inside componentWillMount will not re-run the component again and again, unlike other life-cycle methods.

Note: As per the official React documentation, the life-cycle hook componentWillMount deprecates. It will work until version 17, but you can rename it to UNSAFE_componentWillMount. A componentWillMount hook won’t be able to get access to the native DOM elements because it triggers before the render() function, so elements (HTML) will not be available to use.

Conclusion

The componentWillMount lifecycle hook is an ideal choice when it comes to updating business logic, app configuration updates, and API calls.

Use it wisely because there is a chance that the app will need to be re-run once changes are found. You have learned how to make AJAX API calls and update the initial state values. I hope it will help you.