Life-cycle Events in React JS | YourSite

Life-cycle Events in React JS

React Js 2250 views

Question

1. Life-cycle Events in React JS

• Create a button that will increment the state of a variable count by 1.

• Use anonymous function using arrow function technique in onClick event to call a function handleClick, and update the state of the count variable.

• Use ComponentDidMount, ComponentWillMount,

ComponentDidUpdate, and

ComponentWill Update Life-cycle events, and analyze the order in which they are invoked.

⚫ View the output in the console by inspecting the elements.

Answer


import React, { Component } from 'react';

class App extends React.Component {
  // Initialize the state with a count variable set to 0
  state = {
    count: 0,
  };

  // This function will be called when the button is clicked
  handleClick = () => {
    // Increment the count by 1
    this.setState({ count: this.state.count + 1 });
  };

  // This function is called after the component is mounted
  componentDidMount() {
    console.log('Component did mount');
  }

  // This function is called before the component is mounted
  componentWillMount() {
    console.log('Component will mount');
  }

  // This function is called after the component is updated
  componentDidUpdate() {
    console.log('Component did update');
  }

  // This function is called before the component is updated
  componentWillUpdate() {
    console.log('Component will update');
  }

  // The render function returns the JSX that should be rendered
  render() {
    return (
      <div>
        {/* Display the count */}
        <p>Count: {this.state.count}</p>
        {/* Add a button with an onClick event that calls the handleClick function */}
        <button onClick={() => this.handleClick()}>Increment</button>
      </div>
    );
  }
}


export default App;


🚀 More Blogs You Might Like

Explore more articles and keep learning

Data Science Roadmap: From Complete Beginner to Job-Ready Practitioner
Data-Science
Data Science Roadmap: From Complete Beginner to Job-Ready Practitioner

Data Science Roadmap: From Complete Beginner to Job-Ready Practitioner...

👁 8 2026-07-26
Read More →
How AI Is Changing the Way Software Is Made
Data-Science
How AI Is Changing the Way Software Is Made

How AI Is Changing the Way Software Is Made...

👁 7 2026-07-26
Read More →
8 Mistakes That Quietly Slow Down Talented Developers
Personal-Development
8 Mistakes That Quietly Slow Down Talented Developers

8 Mistakes That Quietly Slow Down Talented Developers...

👁 29 2026-07-12
Read More →
Does religion teach hatred?
islam
Does religion teach hatred?

It is easy to spread hatred in the name of religion, but understanding the true message of religion is much de...

👁 319 2026-06-30
Read More →