← Back to Chapters

State in Class Components

⚛️ State in Class Components

? Quick Overview

In class-based React components, state is used to store and manage data that can change over time. When the state changes, the component automatically re-renders to show the latest UI.

State is defined using this.state (usually inside the constructor) and updated using this.setState(). It plays a role similar to useState in functional components.

State = Dynamic, interactive data

? Key Concepts of this.state

  • State is local to the component and controls how it behaves and what it renders.
  • You initialize state inside the constructor using this.state = {"{}"}.
  • You update state using this.setState(), never by changing this.state directly.
  • Updating state causes the component to re-render with new values.
  • When new state depends on old state, you should use the callback form of setState().

? Syntax & Theory

A typical class component with state:

? View Code Example
// Basic skeleton of a class component with state
class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      value: 0
    };
  }

  render() {
    return <h2>Value: {this.state.value}</h2>;
  }
}

? Explanation

  • constructor(props) runs once when the component is created.
  • this.state holds the initial values.
  • this.state.value is read inside render() to display in the UI.

⚛️ What is State in Class Components?

In class-based components, state is used to store and manage data that changes over time. It allows components to re-render dynamically when data updates, similar to useState in functional components.

You define state inside the constructor using this.state and update it using this.setState().

? Example: Basic Counter

? View Code Example
// Class-based counter using this.state and this.setState()
import React, { Component } from "react";

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

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

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

  reset = () => {
    this.setState({ count: 0 });
  };

  render() {
    return (
      <div>
        <h2>Count: {this.state.count}</h2>
        <button onClick={this.increment}>Increment</button>
        <button onClick={this.decrement}>Decrement</button>
        <button onClick={this.reset}>Reset</button>
      </div>
    );
  }
}

export default Counter;

? Live Output / Explanation

The component shows the current count and three buttons: Increment, Decrement, and Reset.

  • this.state.count holds the current value.
  • this.setState() updates the state and triggers a re-render.
  • Each button calls a method that changes the state in a controlled way.

? Initializing State

You usually define initial state inside the constructor:

? View Code Example
// Initialize multiple state fields inside the constructor
constructor() {
  super();
  this.state = {
    name: "Guest",
    age: 20
  };
}

? Explanation

Always call super() before using this inside the constructor, otherwise this will be undefined.

? Updating State with setState()

State must be updated using this.setState() — never modify this.state directly, otherwise React will not re-render the UI.

? View Code Example
// Correct vs incorrect ways to update state
this.setState({ count: this.state.count + 1 });

// ❌ Wrong: direct mutation (will not trigger re-render)
this.state.count = this.state.count + 1;

? Explanation

The setState() method merges the new state with the existing state and then re-renders the component. Directly changing this.state bypasses React’s update system.

? Using Previous State Safely

When the next state depends on the previous one, use the callback version of setState() to avoid bugs caused by asynchronous updates.

? View Code Example
// Safer way to update based on previous state
this.setState((prevState) => ({
  count: prevState.count + 1
}));

? Explanation

React may batch multiple state updates together. Using prevState guarantees that you always get the most recent value when calculating the next state.

? Multiple State Properties

? View Code Example
// Class component with multiple state fields
class Profile extends Component {
  constructor() {
    super();
    this.state = {
      name: "Riya",
      city: "Pune",
      followers: 100
    };
  }

  updateFollowers = () => {
    this.setState({ followers: this.state.followers + 10 });
  };

  render() {
    return (
      <div>
        <h3>Name: {this.state.name}</h3>
        <p>City: {this.state.city}</p>
        <p>Followers: {this.state.followers}</p>
        <button onClick={this.updateFollowers}>+10 Followers</button>
      </div>
    );
  }
}

? Explanation

React automatically merges the new state with the existing one. When calling this.setState({"{"} followers: ... {"}"}), only the followers property changes — name and city remain the same.

⚡ Important Notes When Using this.state

  • ? Do not modify this.state directly — React won’t re-render.
  • ✅ Prefer arrow functions for class methods to avoid manual binding issues.
  • ⚠️ Remember that setState() is asynchronous — don’t rely on the new value immediately after calling it.

? Tips

  • Initialize state inside the constructor using this.state = {"{}"}.
  • Always use this.setState() to update values instead of directly mutating this.state.
  • Use the callback form of setState() when the next state depends on the previous state.
  • Prefer arrow functions (like increment = () => {"{}"}) to auto-bind this without using .bind(this).

? Try This

  1. Create a class component named ScoreTracker with an initial score of 0.
  2. Add buttons to Increase, Decrease, and Reset the score.
  3. Display the score dynamically on the screen using this.state.score.
  4. Use the callback pattern of setState() when changing the score (for example when incrementing multiple times).

Goal: Learn how to define, update, and render state in class-based React components using this.state and this.setState() to build interactive UIs.