![]() |
VOOZH | about |
ReactJS requires several components to represent a unit of logic for specific functionality. The componentWillMount lifecycle method 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.
componentWillMount() {
// Perform the required
// activity inside it
}
// Call the render method to
// display the HTML contents.
render(){
}
Step 1: Run the below command to create a new project
npx create-react-app my-appStep 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
It will look like the following
Example 1: Using componentWillMount to manipulate the state in a class component.
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.
Steps to Run the application: Use this command in the terminal inside project directory.
npm startOutput: This output will be visible on http://localhost:3000/ on the browser window.
Example 2: This example demonstrate the use of componentWillMount method to make the api calls and display the data in the UI.
Steps to Run the application: Use this command in the terminal inside project directory.
npm startOutput: This output will be visible on http://localhost:3000/ on the browser window.
Note: Changing the state value inside componentWillMount will not re-run the component again and again, unlike other life-cycle methods.