Open In App
Related Articles

React Class Components

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

React Class Components are the JavaScript Classes that extendare React.Component, used to define the UI, and manage the state and events of the application.

Class Components in React

React class components are the bread and butter of most modern web apps built in React JS. These components are simple classes (made up of multiple functions that add functionality to the application) and are based on the traditional class-based approach. All class components are child classes for the Component class of React JS. 

Class Components Examples:

We will learn how to create class components with the help of an example

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 over Functional Components

The main feature of class components that distinguished them from functional components is that they have access to a state which dictates the current behavior and appearance of the component (Later, with React Hooks introduced in version 16.8, we are able to declare a stateful component without declaring a class). This state can be modified by calling the setState() function. One or more variables, arrays, or objects defined as part of the state can be modified at a time with the setState() function.

Implementing state in class components

let us understand how to use state in class components with the help of an example

Example for Implementing State in Class Component:

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

Data is passed to other components with the help of props. Props work similarly for all components in ReactJS be they class or functional. Props are always passed down from the parent component to the child component.

React does not allow a component to modify its own props as a rule. The only way to modify the props is to change the props being passed from the parent component to the child component. This is generally done by passing a reference to a function in the parent component, which changes the props being passed to the child component.

Class Components Props 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

React Lifecycle Methods 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 using 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 : 23 Feb, 2024
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads