React Class Components
Class components were the standard way to write stateful React components before Hooks were introduced in React 16.8. Today, all new code should use function components with Hooks. You’ll still encounter class components in older codebases.
Basic Class Component
import React, { Component } from "react";
class Greeting extends Component {
render() {
// this.props is equivalent to function component props
return <h1>Hello, {this.props.name}!</h1>;
}
}
export default Greeting;
State in Class Components
class Counter extends Component {
// Initialize state in the constructor
constructor(props) {
super(props); // Required โ always call super(props) first
this.state = {
count: 0,
};
}
render() {
return (
<div>
<p>Count: {this.state.count}</p>
{/* Always use setState โ never modify this.state directly */}
<button onClick={() => this.setState({ count: this.state.count + 1 })}>
Increment
</button>
</div>
);
}
}
Lifecycle Methods
class DataFetcher extends Component {
constructor(props) {
super(props);
this.state = { data: null };
}
// Runs after the component mounts (equivalent to useEffect with [])
componentDidMount() {
fetch("/api/data")
.then(res => res.json())
.then(data => this.setState({ data }));
}
// Runs after props or state change (equivalent to useEffect with deps)
componentDidUpdate(prevProps) {
if (prevProps.id !== this.props.id) {
this.fetchData(this.props.id);
}
}
// Cleanup โ runs before component is removed (equivalent to useEffect cleanup)
componentWillUnmount() {
this.subscription.unsubscribe();
}
render() {
return <div>{this.state.data?.name}</div>;
}
}
Class vs Function โ Comparison
| Feature | Class Component | Function Component |
|---|---|---|
| State | this.state + setState |
useState hook |
| Side effects | Lifecycle methods | useEffect hook |
| Sharing logic | HOCs / Render Props | Custom Hooks |
| Code length | More boilerplate | Concise |
| Recommended | Legacy code only | โ All new code |
WarningYou will still encounter class components in older projects and libraries. Knowing how to read them is valuable, but write all new code with function components.