R
Rishtaara
React: The Complete Guide
Lesson 6 of 28Article12 min

Class Components (Legacy Awareness)

Before hooks (2019), React class components were the main way to hold state and lifecycle logic. You extend React.Component and use this.state.

Class Components — what they are

Before hooks (2019), React class components were the main way to hold state and lifecycle logic. You extend React.Component and use this.state.

You will still see class components in old codebases and older tutorials. New projects should use function components + hooks.

Real-life example: Class components are like old landline phones — they still work, but most new homes install smartphones (function components).

Simple class component
import { Component } from "react";

class Welcome extends Component {
  render() {
    return <h1>Hello, {this.props.name}!</h1>;
  }
}

// Usage
<Welcome name="Asha" />

Class state (legacy pattern)

Classes used this.state and this.setState to update data. Lifecycle methods like componentDidMount ran side effects.

Real-life example: this.setState in a class is like updating a paper ledger — you write a new row instead of erasing the old one incorrectly.

Counter with class state
class Counter extends Component {
  state = { count: 0 };

  increment = () => {
    this.setState({ count: this.state.count + 1 });
  };

  render() {
    return (
      <div>
        <p>Count: {this.state.count}</p>
        <button onClick={this.increment}>+1</button>
      </div>
    );
  }
}

Why function components won

Hooks give function components state and effects without classes. Less boilerplate, easier to test, and better TypeScript support.

Real-life example: Hooks are like a universal remote that replaced five separate remotes (constructor, render, lifecycle methods) with one simple device.

  • Write new code with function components + hooks
  • Read class code when maintaining legacy apps
  • Do not mix patterns in one component
Many older tutorials still teach class components for completeness. Know they exist, but build new apps with functions.