React › Class Components & Legacy Lifecycle Methods

What is a class component in React and how does it differ from a function component?

Beginner

Answer

A class component is written using JavaScript class syntax and extends React.Component. It manages state using this.state and this.setState, and it needs a render method that returns the JSX to display. Function components with hooks can do everything class components can, using much simpler and shorter code, which is why almost all new React code today uses function components instead.
class Counter extends React.Component {
  constructor(props) {
    super(props);
    this.state = { count: 0 };
  }
  render() {
    return (
      <button onClick={() => this.setState({ count: this.state.count + 1 })}>
        Count: {this.state.count}
      </button>
    );
  }
}
Real-world example A company maintaining an older codebase built years ago still has class components in production, even though any new features the team adds today are written as function components with hooks.

Common follow-ups: Why did the React team introduce hooks instead of continuing to improve class components?;How would you convert this class component into a function component?