A class component is an ES6 class that extends React.Component, keeps its data in this.state, updates it with this.setState(), and returns its UI from a render() method.
Key features
- Must have a
render() method that returns JSX.
- State is initialised in the constructor (after calling
super(props)); props are read as this.props.
- Has lifecycle methods:
componentDidMount(), componentDidUpdate(), componentWillUnmount(), shouldComponentUpdate().
Advantages
- Built-in state and lifecycle methods give fine control over mounting, updating and cleanup.
- Familiar object-oriented structure (constructor, methods,
this).
- Only class components can act as error boundaries (
componentDidCatch, getDerivedStateFromError).
shouldComponentUpdate / PureComponent help optimise re-rendering.
- Widely used in existing (legacy) React code.
Program: car models
import React from "react";
class Car extends React.Component {
constructor(props) {
super(props);
this.state = { model: props.model, year: props.year };
}
changeModel = () => {
this.setState({ model: this.props.newModel });
};
render() {
return (
<div>
<h2>{this.props.brand}</h2>
<p>Model: {this.state.model} ({this.state.year})</p>
<button onClick={this.changeModel}>Change model</button>
</div>
);
}
}
class App extends React.Component {
render() {
return (
<div>
<Car brand="Tata" model="Nexon" year={2023} newModel="Punch" />
<Car brand="Maruti" model="Swift" year={2022} newModel="Baleno" />
<Car brand="Hyundai" model="Creta" year={2024} newModel="Venue" />
</div>
);
}
}
export default App;
How it works. Each Car receives its brand and starting model through props and copies the model into its own state. render() reads this.state.model to display it. Clicking the button calls setState, which updates the state and makes React re-render only that car with the new model.