Tutorials React JS Class Components
Ch 8 / 47
Chapter 8 Beginner 10 min read React JS

Class Components

Before Hooks arrived in React 16.8, Class Components were the only way to add state and lifecycle logic to your UI. Understanding them is essential — you will encounter them in real codebases, legacy projects, and interviews. In this chapter you will learn the ES6 class syntax, how to use this.state and this.setState(), what the lifecycle methods are, how props work in class components, and when class components still make sense today.

Advertisement
What you'll learn
What a class component is — ES6 class extending React.Component
The constructor() — initialising state and binding methods
this.state & this.setState() — reading and updating state
The render() method — the required JSX return point
Lifecycle methods — mount, update, unmount phases
Props in class components — reading via this.props
Class vs functional comparison — side-by-side the same component
When to use class components — practical guidance

1. What is a Class Component?

A Class Component is a React component written as an ES6 JavaScript class that extends React.Component. It must include a render() method that returns JSX.

Before React 16.8 (2019), class components were the only way to manage state and run side effects. Today, functional components with Hooks are preferred — but class components still power millions of production apps and appear in every React interview.

One-line definition A class component = an ES6 class that extends React.Component and has a render() method that returns JSX.
Historical Importance
Class components were the standard React pattern from 2015–2019. All pre-hooks codebases, open-source libraries, and tutorials use them. You must be able to read and update this code.
Legacy
Error Boundaries
The componentDidCatch lifecycle method still only works in class components. If you need an Error Boundary, you must write a class component (as of React 18).
Still required
Interview Essential
Lifecycle methods, this.setState(), and the class/functional comparison are standard React interview questions at every level — junior to senior.
Career
Understand Hooks Better
Knowing lifecycle methods makes useEffect much easier to understand — because useEffect was designed to replace lifecycle methods.
Foundation

2. Class Component Syntax

Here is the minimum structure every class component must have:

jsx — Greeting.jsx — minimum class component
import React, { Component } from 'react';

// Step 1: extend React.Component
class Greeting extends Component {

  // Step 2: render() is required — returns JSX
  render() {
    return (
      <div>
        <h1>Hello from a class component!</h1>
      </div>
    );
  }
}

export default Greeting;

Every class component has the same 4-part skeleton:

1
class keyword
Define a class with a PascalCase name that extends Component (or React.Component).
class Name extends Component
2
constructor()
Optional — call super(props) first, then initialise this.state and bind event handlers.
optional
3
Methods
Lifecycle methods, custom event handlers, and helper functions — all defined as class methods.
componentDidMount etc.
4
render()
Required. Must return JSX. Called every time state or props change. Must be pure — no side effects inside.
required

3. State & this.setState()

In a class component, state is a plain object stored on this.state. You initialise it in the constructor and always update it through this.setState() — never by mutating this.state directly.

jsx — Counter.jsx — state with this.state & this.setState()
import React, { Component } from 'react';

class Counter extends Component {

  // 1. Initialise state in constructor
  constructor(props) {
    super(props);            // ALWAYS call super(props) first
    this.state = {
      count: 0,
    };
  }

  // 2. Update state with this.setState() — NEVER mutate directly
  increment = () => {
    this.setState({ count: this.state.count + 1 });
  };

  decrement = () => {
    this.setState({ count: this.state.count - 1 });
  };

  // 3. Read state with this.state.propertyName
  render() {
    return (
      <div>
        <h2>Count: {this.state.count}</h2>
        <button onClick={this.increment}>+</button>
        <button onClick={this.decrement}>−</button>
      </div>
    );
  }
}

export default Counter;
setState is asynchronous this.setState() does not update the state immediately. React batches updates for performance. If your new state depends on the current state, always use the updater function form:
this.setState(prevState => ({ count: prevState.count + 1 }))
This guarantees you always read the latest value, not a stale one.
jsx — two ways to call setState
// ❌ Risky when new state depends on old state
this.setState({ count: this.state.count + 1 });

// ✅ Safe — always use updater function for derived state
this.setState(prevState => ({
  count: prevState.count + 1
}));

// Callback after state is applied (like useEffect with the value)
this.setState({ count: 10 }, () => {
  console.log('State updated!', this.state.count); // 10
});
Advertisement

4. Props in Class Components

Props work the same way as in functional components — data flows from parent to child. In a class component you access them via this.props instead of a function parameter.

jsx — WelcomeCard.jsx — using this.props
class WelcomeCard extends Component {
  render() {
    // Access props via this.props
    const { name, role, city } = this.props;

    return (
      <div className="card">
        <h2>Hello, {name}!</h2>
        <p>Role: {role}</p>
        <p>City: {city}</p>
      </div>
    );
  }
}

// Usage — pass props like HTML attributes
<WelcomeCard
  name="Priya"
  role="React Developer"
  city="Vadodara"
/>
Props in constructor If you need props inside constructor(), pass them to super(props). Otherwise React won't set this.props in the constructor body and you'll get undefined if you try to read this.props there. Outside the constructor, this.props always works fine.
jsx — default props with static defaultProps
class WelcomeCard extends Component {
  render() {
    return <h2>Hello, {this.props.name}!</h2>;
  }
}

// Default props — used when the parent does not pass a prop
WelcomeCard.defaultProps = {
  name: 'Guest',
};

// <WelcomeCard />  →  "Hello, Guest!"

5. Lifecycle Methods

Every class component goes through three lifecycle phases: Mounting (component appears on screen), Updating (state or props changed), and Unmounting (component is removed). React calls specific methods at each stage — you override them to run your own logic.

Mounting — component added to the DOM
constructor(props)
Runs first. Initialise this.state and bind methods. Call super(props) as the very first line.
runs once
render()
Returns the JSX. Must be pure — no side effects, no API calls. Runs on mount and every update.
required
componentDidMount()
Runs after the component is in the DOM. Perfect for API calls, subscriptions, and DOM measurements. Equivalent to useEffect(..., []).
fetch data here
Updating — state or props changed
shouldComponentUpdate(nextProps, nextState)
Return true to allow re-render, false to block it. Used for manual performance optimisation — rarely needed in practice.
performance
render()
Same method as mount — React calls it again with updated state/props to produce the new JSX snapshot.
runs again
componentDidUpdate(prevProps, prevState)
Runs after every update. Use to react to prop/state changes — e.g. fetch new data when a prop changes. Always wrap API calls in a condition to avoid infinite loops.
react to changes
Unmounting — component removed from DOM
componentWillUnmount()
Runs just before the component is destroyed. Clean up subscriptions, timers, event listeners, and anything else that would cause memory leaks. Equivalent to the cleanup function returned from useEffect.
cleanup here
jsx — DataLoader.jsx — all three phases in one component
class DataLoader extends Component {
  constructor(props) {
    super(props);
    this.state = { data: null, loading: true };
  }

  // ── MOUNT: fetch data after component is in the DOM ──
  componentDidMount() {
    fetch(`https://api.example.com/users/${this.props.userId}`)
      .then(res => res.json())
      .then(data => this.setState({ data, loading: false }));
  }

  // ── UPDATE: re-fetch when userId prop changes ─────────
  componentDidUpdate(prevProps) {
    if (prevProps.userId !== this.props.userId) {
      this.setState({ loading: true });
      fetch(`https://api.example.com/users/${this.props.userId}`)
        .then(res => res.json())
        .then(data => this.setState({ data, loading: false }));
    }
  }

  // ── UNMOUNT: cancel anything that could leak ─────────
  componentWillUnmount() {
    console.log('DataLoader removed — clean up here');
  }

  render() {
    if (this.state.loading) return <p>Loading…</p>;
    return <pre>{JSON.stringify(this.state.data, null, 2)}</pre>;
  }
}

6. Event Binding — Fixing the this Problem

The trickiest part of class components is event handler binding. In JavaScript, regular class methods lose their this context when passed as a callback. You have three common solutions:

jsx — three ways to bind event handlers in class components
class BindingExamples extends Component {
  constructor(props) {
    super(props);
    this.state = { msg: '' };

    // Method 1 — bind in constructor (classic, works everywhere)
    this.handleClick1 = this.handleClick1.bind(this);
  }

  handleClick1() {
    this.setState({ msg: 'Bound in constructor' });
  }

  // Method 2 — class field arrow function (modern, most common ✅)
  handleClick2 = () => {
    this.setState({ msg: 'Arrow class field' });
  };

  render() {
    return (
      <div>
        <button onClick={this.handleClick1}>Method 1</button>
        <button onClick={this.handleClick2}>Method 2</button>

        {/* Method 3 — inline arrow (avoid in real code — creates new fn every render) */}
        <button onClick={() => this.setState({ msg: 'Inline arrow' })}>
          Method 3
        </button>

        <p>{this.state.msg}</p>
      </div>
    );
  }
}
Best practice today Use class field arrow functions (Method 2) — they are the cleanest syntax, automatically bind this, and are supported by all modern setups. Avoid inline arrows in JSX (Method 3) if the component renders frequently, because a new function is created on every render.
⭐⭐⭐⭐⭐
4.9 / 5
🔥 Most Popular at K2infocom · Vadodara
React JS Complete
Masterclass
From Class Components & Hooks all the way to full-stack React apps. State, Context, Router, Redux, REST APIs & 6 real-world projects — guided by experts in Vadodara.
Class & Functional Hooks & State React Router Redux Toolkit REST APIs 6 Projects Certificate
2,500+Students
6+Projects
3–6Months
100%Placement

7. Class vs Functional — Same Counter, Two Styles

The best way to understand the difference is to build the same component both ways. Both produce identical output — the difference is in how much code you write:

Class Component
class Counter extends Component {
  constructor(props) {
    super(props);
    this.state = { count: 0 };
  }

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

  render() {
    return (
      <div>
        <p>{this.state.count}</p>
        <button
          onClick={this.increment}
        >+1</button>
      </div>
    );
  }
}
Functional Component ✅
import { useState } from 'react';

function Counter() {
  const [count, setCount] =
    useState(0);

  return (
    <div>
      <p>{count}</p>
      <button
        onClick={() =>
          setCount(c => c + 1)
        }
      >+1</button>
    </div>
  );
}
Feature Class Component Functional Component
Syntax ES6 class extending Component Plain JS function
State this.state + this.setState() useState() Hook
Side effects componentDidMount/Update useEffect() Hook
Hooks support ✗ Not supported ✓ Full support
Boilerplate constructor, super, render() None
this binding Must bind event handlers Not needed
Error Boundary ✓ componentDidCatch works ✗ Not available
Recommended for new code Legacy only ✓ Always

8. When to Use Class Components

For any new code, always use functional components. The only cases where you still write a class component in 2024+ are:

Error Boundaries
componentDidCatch() and getDerivedStateFromError() are only available in class components. You need a class component to catch render errors in a subtree.
Only option
Maintaining Legacy Code
When working on an existing codebase that uses class components, you often must understand, fix, and extend them without rewriting everything to functional.
Real-world work
Interview Preparation
Interviewers regularly ask about lifecycle methods, setState async behaviour, and class vs functional differences. Knowing both styles gives you a real advantage.
Career
Third-party Library Docs
Many popular library documentation pages still show class component examples. Being able to read and adapt them to your functional codebase is a daily skill.
Practical
Advertisement
Knowledge Check — Class Components
Q1. What two things are always required in a class component?
A class component requires: (1) the class must extend React.Component (or Component if imported), and (2) the class must have a render() method that returns JSX.

The constructor is optional — only needed if you want to initialise this.state or bind methods. Everything else (lifecycle methods, class fields) is also optional.
Q2. Why must you call super(props) first inside the constructor?
In JavaScript, a subclass constructor must call super() before using this. Without it, the JavaScript engine throws a ReferenceError ("Must call super constructor before accessing 'this'").

Passing props to super(props) ensures this.props is available inside the constructor body. If you call super() without props, this.props will be undefined inside the constructor (though it works fine in other methods).
Q3. What is the equivalent of componentDidMount in a functional component?
componentDidMount() runs once after the component mounts. The functional equivalent is:

useEffect(() => { /* your code */ }, [])

The empty dependency array [] tells React to run the effect only once — after the first render — which mirrors componentDidMount exactly.

Similarly:
• componentDidUpdate → useEffect with dependencies
• componentWillUnmount → cleanup function returned from useEffect
Q4. Why should you never mutate this.state directly?
React only knows to re-render a component when you call this.setState(). If you mutate this.state directly (e.g. this.state.count = 5), the state object changes in memory but React never finds out — so the UI does not update.

Always use this.setState() which: (1) merges your update into state, (2) tells React a re-render is needed, and (3) batches multiple updates for performance.
Multiple Choice
MCQ 1
Which class component lifecycle method is equivalent to useEffect(() => {}, []) in a functional component?
MCQ 2
You call this.setState({ count: this.state.count + 1 }) three times in a row. How many times will the component re-render?
MCQ 3
Which lifecycle method should you use to unsubscribe from a WebSocket connection when a component is removed?
MCQ 4
In 2024, which is the only scenario where you MUST write a class component in React?
Chapter 8 Summary — Class Components
  • A Class Component is an ES6 class that extends React.Component and must have a render() method that returns JSX.
  • State is initialised in constructor() as this.state = {}. Always update via this.setState() — never mutate directly.
  • Use the updater function form of setState (setState(prev => ...)) when new state depends on old state, because setState is asynchronous.
  • Props are accessed via this.props. Always call super(props) first in the constructor to make this.props available there.
  • Lifecycle phases: Mount (constructor → render → componentDidMount), Update (render → componentDidUpdate), Unmount (componentWillUnmount).
  • Event handlers need to be bound to this — use class field arrow functions for the cleanest approach.
  • Functional components with Hooks are preferred for all new code. Class components are still required for Error Boundaries and maintaining legacy code.
  • Hook equivalents: componentDidMount → useEffect(fn, []), componentWillUnmount → cleanup return from useEffect.
Practice — Convert a Class Component
Open the sandbox and write a class component <TodoList /> with state — then rewrite it as a functional component with useState. Compare both side-by-side.
Open Vite + React Sandbox

Rate Us on Google

4.8 / 5
Enjoying this tutorial?
Your 5-star review helps other learners discover our free tutorials and encourages us to keep creating quality content.
80+ reviews
Write a Google Review
Join WhatsApp Channel