Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • React Tutorial
  • React Exercise
  • React Basic Concepts
  • React Components
  • React Props
  • React Hooks
  • React Router
  • React Advanced
  • React Examples
  • React Interview Questions
  • React Projects
  • Next.js Tutorial
  • React Bootstrap
  • React Material UI
  • React Ant Design
  • React Desktop
  • React Rebass
  • React Blueprint
  • JavaScript
  • Web Technology
Open In App
Next Article:
What is ComponentWillMount() method in ReactJS ?
Next article icon

What is ComponentWillMount() method in ReactJS ?

Last Updated : 30 Oct, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

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. 

Prerequisites

  • React JS
  • React JS class components

ComponentWillMount() method

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:

componentWillMount() {
// Perform the required
// activity inside it
}
// Call the render method to
// display the HTML contents.
render(){
}
  • 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.

Creating React Application

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

Example 1: Using componentWillMount to manipulate the state in a class component.

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.

Steps to Run the application: Use this command in the terminal inside project directory.

npm start

Output: 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.

JavaScript
import React, { Component } from "react";  class ApiCall extends Component {     constructor() {         super();         this.state = {             todo: {},         };     }      componentWillMount() {         fetch(             "https://jsonplaceholder.typicode.com/todos/3"         )             .then((response) => response.json())             .then((json) => {                 this.setState({ todo: json });             });     }      render() {         const { todo } = this.state;         console.log(todo);         return (             <div                 style={{                     textAlign: "center",                     margin: "auto",                     width: "300px",                 }}             >                 <h1 style={{ color: "green" }}>                     GeeksforGeeks                 </h1>                 <h3>                     React Example for API call inside                     componentWillMount Method                 </h3>                 <br />                 <h4>API call </h4>                 <b>Todo title : </b>                 {todo.title}                 <p>                     <b>Todo completed :</b>                     {todo.completed === true                         ? "true"                         : "false"}                 </p>             </div>         );     } }  export default ApiCall; 

Steps to Run the application: Use this command in the terminal inside project directory.

npm start

Output: This output will be visible on http://localhost:3000/ on the browser window.

Peek-2023-10-26-17-33

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


Next Article
What is ComponentWillMount() method in ReactJS ?

N

nitinshukla413
Improve
Article Tags :
  • Web Technologies
  • ReactJS
  • React-Questions

Similar Reads

    ReactJS componentWillUnmount() Method
    In React, lifecycle methods allow you to manage the behaviour of components at different stages of their existence. One important lifecycle method for cleaning up resources and side effects is componentWillUnmount(). This method is called just before a component is removed from the DOM, making it an
    5 min read
    ReactJS UNSAFE_componentWillMount() Method
    The componentWillMount() method invokes right before our React component gets loaded or mounted in the DOM (Document Object Model). It is called during the mounting phase of the React Life-cycle, i.e., before render(). It is used to fetch data from outside the component by executing the React code s
    3 min read
    ReactJS componentDidMount() Method
    In React, componentDidMount() is a lifecycle method in React that is called once a component has been rendered and placed in the DOM. This method is invoked only once during the lifecycle of a component, immediately after the first render, which is why it is useful for operations like fetching data,
    7 min read
    ReactJS UNSAFE_componentWillUpdate() Method
    The componentWillUpdate() method provides us the control to manipulate our React component just before it receives new props or state values. It is called just before the rendering of our component during the updating phase of the React Life-cycle ,i.e., this method gets triggered after the updation
    3 min read
    When is the componentWillUnmount method called?
    The componentWillUnmount() method allows us to execute the React code when the component gets destroyed or unmounted from the DOM (Document Object Model). This method is called during the Unmounting phase of the React Life-cycle i.e. before the component gets unmounted. Prerequisites:NPM & NodeR
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences