React Class Components (original) (raw)

Last Updated : 26 Apr, 2025

Class components are ES6 classes that extend React.Component. They allow state management and lifecycle methods for complex UI logic.

The render() method in React class components returns JSX elements describing the UI of the Application.

**Here is a simple class component in React

JavaScript `

// Filename App.js import React from "react";

class App extends React.Component { render() { return

GeeksForGeeks

; } }

export default App;

`

React-class-component

React Class Components

Structure of React Class Components

A typical React class component consists of the following parts:

class MyComponent extends React.Component { ... }

constructor(props) {
super(props);
this.state = { count: 0 }; // Initialize state
}

render() {
return

Current count: {this.state.count}
;
}

this.state = {
count: 0
};

**Event Handlers: Event handlers are typically methods in the class. They are used to handle user interactions like clicks, form submissions, etc. These methods often use this.setState() to update the component's state.

increment = () => {
this.setState({ count: this.state.count + 1 });
};

class MyComponent extends React.Component {
render() {
return

{this.props.name}
; // Access props
}
}

Lifecycle Methods

Lifecycle methods allow components to execute code at specific stages of their existence. **Class components have access to the React lifecycle methods. They are divided into three phases:

1. Mounting

These methods run when a component is created and added to the DOM

componentDidMount() {
console.log('Component Mounted');
}

2. Updating

Called when a component’s state or props change

componentDidUpdate(prevProps, prevState) {
console.log('Component Updated');
}

3. Unmounting

This method runs when a component is removed from the DOM

componentWillUnmount() {
console.log('Component Will Unmount');
}

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.

Advantages of Class Components

Limitations of Class Components