Components & Props
React Class Components
A class component extends React.Component and defines a render method that returns JSX. State lives in this.state and is updated with this.setState. Classes are legacy for new code but still common in codebases written before 2020.
What is Class Components in React?
A class component extends React.Component and defines a render method that returns JSX. State lives in this.state and is updated with this.setState. Classes are legacy for new code but still common in codebases written before 2020.
Why Class Components matters
You will meet classes when maintaining older projects, in error boundaries (still the only class-only feature), and in interview questions that compare the two styles.
Class Components example
import { Component } from 'react';
class Counter extends Component {
state = { count: 0 };
increment = () => {
this.setState(prev => ({ count: prev.count + 1 }));
};
render() {
return <button onClick={this.increment}>{this.state.count}</button>;
}
}How this works
increment is written as a class field arrow function so that this stays bound to the instance. Written as a normal method it would need binding in the constructor — the classic source of "cannot read property setState of undefined".
Class vs function components
| Concern | Class | Function + hooks |
|---|---|---|
| State | this.state / this.setState | useState / useReducer |
| Side effects | componentDidMount, componentDidUpdate, componentWillUnmount | useEffect |
| Reusing logic | HOCs and render props | custom hooks |
| this binding | required | not applicable |
| New React features | no | yes |
Common mistakes with Class Components
- Forgetting to bind a method, so this is undefined inside it.
- Calling this.setState({ count: this.state.count + 1 }) in a loop — updates batch and you lose increments.
- Writing new components as classes out of habit.
React Class Components— Interview Questions & FAQs
Are class components deprecated?+
They are not removed and existing code keeps working, but they receive no new features and the documentation is written for function components. Write new components as functions.
