Open In App

React Class Components

Improve
Improve
Like Article
Like
Save
Share
Report

React class components are the backbone of most modern web applications built using React JS. In this article, we’ll learn what class components are, their advantages, how to manage the state and events of the application and how to use them effectively.

What Are React Class Components?

React class components are simple classes that extend React.Component. They define the UI, manage state, and handle events within your application. Unlike functional components, which are based on function syntax, class components follow the traditional class-based approach.

Class Components Examples

Example 1: Create Class Component in React

Program to demonstrate the creation of class components. Create a React app and edit the App.js as:

javascript
// Filename App.js

import React from "react";

class App extends React.Component {
  render() {
    return <h1>GeeksForGeeks</h1>;
  }
}

export default App;

 Output: 

React Class Component Example - Output

Once a component is declared, it can be used in other components. Program to demonstrate the use of class components in other components. 

Example 2: Using Class Components in react

This example demonstrate the creation and use of class component Sample.

javascript
// Filename - App.js

import React from "react";

class Sample extends React.Component {
  render() {
    return <h1>A Computer Science Portal For Geeks</h1>;
  }
}

class App extends React.Component {
  render() {
    return <Sample />;
  }
}

export default App;

Output: 

React Class Component Example - Output

Advantages of Class Components

  1. State Management:
    • Class components have access to state, allowing you to manage dynamic data efficiently.
    • Use this.setState() to modify state variables.
  2. Lifecycle Methods:
    • Class components offer lifecycle methods like componentDidMount, componentDidUpdate, and componentWillUnmount.
    • These methods allow you to perform actions at specific points in a component’s lifecycle.

Implementing state in class components

Let’s create an example where we toggle a welcome message:

Example: Program to demonstrate the use of state in class components.

javascript
// Filename - App.js

import React from "react";

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = { change: true };
  }
  render() {
    return (
      <div>
        <button
          onClick={() => {
            this.setState({ change: !this.state.change });
          }}
        >
          Click Here!
        </button>
        {this.state.change ? (
          <h1>Welcome to GeeksforGeeks</h1>
        ) : (
          <h1>A Computer Science Portal for Geeks</h1>
        )}
      </div>
    );
  }
}

export default App;

Output:

Passing props in Class Components

When working with React components, understanding props is essential. Props allow data to flow from parent components to child components, enabling dynamic content and efficient communication within your application. Whether you’re dealing with class components or functional components, the principles remain consistent.

Example: Program to demonstrate the use of props in class components.

javascript
// Filename - App.js

import React from "react";

class App extends React.Component {
  render() {
    return <h1>{this.props.data}</h1>;
  }
}

class propsExample extends React.Component {
  constructor(props) {
    super(props);
    this.state = { change: true };
  }
  render() {
    return (
      <div>
        <button
          onClick={() => {
            this.setState({ change: !this.state.change });
          }}
        >
          Click Here!
        </button>
        {this.state.change ? (
          <App data="Welcome to GeeksforGeeks" />
        ) : (
          <App data="A Computer Science Portal for Geeks" />
        )}
      </div>
    );
  }
}

export default App;

Output:

Lifecycle methods in Class Components

Class components have access to the React lifecycle methods

Lifecycle Method

Description

componentWillMount()

used to implement server-side logic before the actual rendering happens, such as making an API call to the server

componentDidMount()

allows us to execute the React code when the component is already placed in the DOM (Document Object Model)

componentWillReceiveProps()

used to update the state in response to some changes in our props.

componentWillUpdate()

provides us the control to manipulate our React component just before it receives new props or state values.

shouldComponentUpdate()

allows us to exit the complex react update life cycle to avoid calling it again and again on every re-render.

render()

used to display the component on the UI returned as HTML or JSX components.

componentWillUnmount()

llows us to execute the React code when the component gets destroyed or unmounted from the DOM.

These lifecycle functions are called at different stages of the lifecycle and are used for a variety of purposes like changing the state or doing some work (like fetching data from an external API). They are also referred to as lifecycle hooks. 

Example: Program to demonstrate the use of lifecycle methods.

javascript
// Filename - App.js

import React from "react";

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = { text: "Welcome!" };
  }

  componentWillMount() {
    this.setState({
      text: "GeeksforGeeks",
    });
  }

  render() {
    return <h1>{this.state.text}</h1>;
  }
}

export default App;

 Output: 

Lifecycle method in class component example - output

Disadvantages of Class Components

Class components are slightly slower than their functional counterparts. The difference is very small and is almost negligible for smaller web apps – though the performance difference increases when the number of components in the app increases. Moreover, class components involve a lot more coding on the programmer’s part, making them slightly more inefficient to use.



Last Updated : 19 Mar, 2024
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads