How to Use componentWillMount in React
Jul 31, 2020 • 4 Minute Read
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.
constructor() {
super();
this.state = {
message: "This is initial message"
};
}
As shown above, there is one state variable called message with a default string. Now update the message as shown below.
componentWillMount() {
this.setState({ message: "This is an updated message" });
}
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.
render() {
return (
<div>
<p>Update the state</p>
<hr />
{this.state.message}
</div>
);
}
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.
componentWillMount() {
fetch("https://jsonplaceholder.typicode.com/todos/1")
.then(response => response.json())
.then(json => {
this.setState({ todo: json });
});
}
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.
this.setState({ todo: json });
After getting the response from the API, you can consume the data as per your requirements. Below is a complete example of this.
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;
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.