Author avatar

Gaurav Singhal

How to Use componentWillMount in React

Gaurav Singhal

  • Jul 31, 2020
  • 4 Min read
  • 71 Views
  • Jul 31, 2020
  • 4 Min read
  • 71 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.

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

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

1
2
3
componentWillMount() {
    this.setState({ message: "This is an updated message" });
}
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.

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

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

1
this.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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
import React, { Component } from "react";

class ApiCall extends Component {
  constructor() {
    super();
    this.state = {
      todo: {}
    };
  }

  componentWillMount() {
    fetch("https://jsonplaceholder.typicode.com/todos/1")
      .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;
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.

0