Prior to the introduction of React Hooks in version 16.8, Class Components were the only way to manage component state and handle side-effects via lifecycle methods in React.
While functional components with hooks are now the modern standard, understanding class components remains important for maintaining legacy codebases.
flowchart LR
Mount["Mounting (componentDidMount)"] --> Update["Updating (componentDidUpdate)"]
Update --> Unmount["Unmounting (componentWillUnmount)"]
import React, { Component } from 'react';
class Clock extends Component {
constructor(props) {
super(props);
// Initialize component state
this.state = {
time: new Date().toLocaleTimeString(),
};
}
// Lifecycle Method: Runs after component mounts to DOM
componentDidMount() {
this.timerID = setInterval(() => {
this.setState({ time: new Date().toLocaleTimeString() });
}, 1000);
}
// Lifecycle Method: Runs before component unmounts from DOM
componentWillUnmount() {
clearInterval(this.timerID);
}
render() {
return (
<div className="clock-widget">
<h2>{this.props.label}</h2>
<p>Current Time: {this.state.time}</p>
</div>
);
}
}
export default Clock;
| Aspect | Class Component (Legacy) | Functional Component (Modern) |
|---|---|---|
| State Declaration | this.state = { count: 0 } |
const [count, setCount] = useState(0) |
| State Mutation | this.setState({ count: 1 }) |
setCount(1) |
| Side Effects | componentDidMount / componentWillUnmount |
useEffect(() => { ... return () => cleanup }, []) |
this Binding |
Required manual binding or arrow functions | Not applicable (this is not used) |
super(props): In ES6 class constructors, super(props) must be called before accessing this.props.this.state.count = 5 will not trigger a re-render. Always use this.setState().Convert the Clock class component above into a functional component using useState and useEffect.
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.