Before React 16.8 introduced Hooks, React class components were the only way to store local state and run lifecycle callbacks. A class component extends React.Component, defines a render() method that returns JSX, and manages state through this.state and this.setState().
While modern React projects use function components, you will still encounter class components in older codebases and in Error Boundaries. Here is how state initialization and updates work inside a class.
import { Component } from 'react';
export class TimerCard extends Component {
constructor(props) {
super(props);
this.state = { seconds: 0 };
}
componentDidMount() {
this.timerId = setInterval(() => {
this.setState((prev) => ({ seconds: prev.seconds + 1 }));
}, 1000);
}
componentWillUnmount() {
clearInterval(this.timerId);
}
render() {
return (
<section>
<h2>Elapsed Time: {this.state.seconds}s</h2>
</section>
);
}
}
Class components expose explicit lifecycle hooks such as componentDidMount for fetching data or starting timers, componentDidUpdate for reacting to prop changes, and componentWillUnmount for cleaning up subscriptions before removal. Understanding this mapping makes migrating older screens to function components straightforward.
| Class Lifecycle | Modern Hook Equivalent | Purpose |
|---|---|---|
constructor / this.state |
useState |
Initialize local state |
componentDidMount |
useEffect(..., []) |
Run code after mount |
componentDidUpdate |
useEffect(..., [deps]) |
React to prop/state changes |
componentWillUnmount |
Cleanup inside useEffect |
Clear timers and listeners |
this.state Directly: Writing this.state.seconds = 5 never triggers a re-render. Always call this.setState(...).this Binding on Methods: Passing onClick={this.handleClick} on a regular class method loses this context unless you bind it in the constructor or use an arrow class field.componentWillMount and componentWillReceiveProps cause race conditions in concurrent rendering and should be replaced.No. React recommends function components with Hooks for all new components because hooks avoid this binding bugs and simplify logic reuse.
No. Class components still work in React 19, and Error Boundaries (componentDidCatch and getDerivedStateFromError) still require class syntax.
this.setState overwrite all state properties?No. Unlike the useState setter, this.setState performs a shallow merge with existing this.state properties.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
You've completed this section! Take a quick 5-question quiz to check your understanding.