Understand React Class-Based Components

In the early days, class-based components were the only way to manage complex states and lifecycles.

While Functional Components and Hooks are popular now, understanding classes is still vital for any serious developer.

In this tutorial, I will show you exactly how to work with React class-based components. I’ll use examples you might encounter in a professional US-based project, like a payroll or real estate dashboard.

What is a React Class-Based Component?

A class component is a regular JavaScript class that extends the React.Component library. It acts as a blueprint for creating UI elements that need to hold their own private data.

In my experience, classes provide a very structured way to organize code, especially for large enterprise applications.

To create one, you must include a render() method that returns the HTML (JSX) for your application.

Set Up a Basic Class Component

Before we dive into the complex logic, let’s look at the basic structure. I always start by importing React and the Component class from the package.

Here is a simple example of a “Company Profile” component for a tech firm based in San Francisco.

import React, { Component } from 'react';

class CompanyProfile extends Component {
  render() {
    return (
      <div style={{ padding: '20px', border: '1px solid #ccc' }}>
        <h1>TechSolutions Inc.</h1>
        <p>Location: San Francisco, California</p>
        <p>Industry: Cloud Computing</p>
      </div>
    );
  }
}

export default CompanyProfile;

You can see the output in the screenshot below.

React Class-Based Components

In this code, the render() method is mandatory. It tells React what should appear on the screen.

Work with State in Class Components

One of the biggest reasons I used classes for years was the state object.

State allows a component to “remember” information and update the UI when that information changes.

In a US-based banking app, for example, you might need to track a user’s account balance.

To initialize state, we use a constructor method.

Example: Bank Account Balance Tracker

import React, { Component } from 'react';

class BankAccount extends Component {
  constructor(props) {
    super(props);
    // Initializing the state
    this.state = {
      balance: 5000,
      accountType: 'Savings',
      currency: 'USD'
    };
  }

  depositMoney = () => {
    this.setState({
      balance: this.state.balance + 1000
    });
  }

  render() {
    return (
      <div style={{ textAlign: 'center', marginTop: '50px' }}>
        <h2>US Bank Account Summary</h2>
        <p>Account Type: {this.state.accountType}</p>
        <p>Current Balance: {this.state.balance} {this.state.currency}</p>
        <button onClick={this.depositMoney} style={{ padding: '10px 20px', cursor: 'pointer' }}>
          Deposit $1,000
        </button>
      </div>
    );
  }
}

export default BankAccount;

You can see the output in the screenshot below.

Understand React Class-Based Components

I always use this.setState() to update the data. Never modify this.state directly, as it won’t trigger a re-render.

Use Props in Class Components

Props are used to pass data from a parent component to a child component. In a real estate listing app, you might pass the property price and address as props.

Inside a class component, you access these using this.props.

Example: Real Estate Listing

import React, { Component } from 'react';

class PropertyListing extends Component {
  render() {
    return (
      <div style={{ margin: '15px', border: '2px solid blue', borderRadius: '8px', padding: '10px' }}>
        <h3>Property Details</h3>
        <p><strong>Address:</strong> {this.props.address}</p>
        <p><strong>Price:</strong> ${this.props.price}</p>
        <p><strong>Listing Agent:</strong> {this.props.agent}</p>
      </div>
    );
  }
}

// Parent Component usage
class PropertyApp extends Component {
  render() {
    return (
      <div>
        <PropertyListing address="123 Maple Ave, New York, NY" price="850,000" agent="John Smith" />
        <PropertyListing address="456 Oak St, Austin, TX" price="425,000" agent="Sarah Jenkins" />
      </div>
    );
  }
}

export default PropertyApp;

You can see the output in the screenshot below.

Class-Based Components in React

This method makes your components reusable across different parts of your US-wide application.

Understand Lifecycle Methods

Lifecycle methods are special functions that run at specific points in a component’s life.

I find these incredibly useful for fetching data from APIs or setting up timers.

1. componentDidMount()

This runs immediately after the component is added to the DOM. It’s the best place for API calls.

2. componentDidUpdate()

This runs whenever the state or props change. Use it to perform logic based on the update.

3. componentWillUnmount()

This runs just before the component is destroyed. It’s perfect for cleaning up subscriptions or intervals.

Example: Live Stock Price Tracker (NASDAQ)

import React, { Component } from 'react';

class StockTracker extends Component {
  constructor(props) {
    super(props);
    this.state = {
      price: 150.25,
      lastUpdated: new Date().toLocaleTimeString('en-US')
    };
  }

  componentDidMount() {
    // Simulating an API call to fetch Apple (AAPL) stock price
    this.timerID = setInterval(() => this.updatePrice(), 5000);
    console.log("Stock Tracker mounted.");
  }

  componentWillUnmount() {
    // Cleaning up the timer to prevent memory leaks
    clearInterval(this.timerID);
    console.log("Stock Tracker unmounted.");
  }

  updatePrice() {
    // Randomly fluctuating the price for demonstration
    const change = (Math.random() * 2 - 1).toFixed(2);
    this.setState({
      price: (parseFloat(this.state.price) + parseFloat(change)).toFixed(2),
      lastUpdated: new Date().toLocaleTimeString('en-US')
    });
  }

  render() {
    return (
      <div style={{ backgroundColor: '#f4f4f4', padding: '20px', borderRadius: '10px' }}>
        <h2>Live NASDAQ: AAPL</h2>
        <p style={{ fontSize: '24px', color: 'green' }}>${this.state.price}</p>
        <p>Last Updated (EST): {this.state.lastUpdated}</p>
      </div>
    );
  }
}

export default StockTracker;

In my career, I’ve seen many memory leaks caused by forgetting to use componentWillUnmount. Always clean up your intervals!

Handle Events in Classes

Handling clicks or form inputs in classes requires a bit of attention to “this” binding.

I prefer using arrow functions for event handlers because they automatically bind to the class instance.

Example: US Voter Registration Check

import React, { Component } from 'react';

class VoterEligibility extends Component {
  constructor(props) {
    super(props);
    this.state = {
      age: '',
      message: ''
    };
  }

  handleInputChange = (event) => {
    this.setState({ age: event.target.value });
  }

  checkEligibility = () => {
    const age = parseInt(this.state.age);
    if (age >= 18) {
      this.setState({ message: 'You are eligible to vote in the upcoming US Election!' });
    } else {
      this.setState({ message: 'You must be at least 18 years old to register.' });
    }
  }

  render() {
    return (
      <div style={{ padding: '30px' }}>
        <h3>Voter Registration Status</h3>
        <input 
          type="number" 
          placeholder="Enter your age" 
          value={this.state.age} 
          onChange={this.handleInputChange}
          style={{ padding: '8px', marginRight: '10px' }}
        />
        <button onClick={this.checkEligibility} style={{ padding: '8px 15px' }}>
          Check Status
        </button>
        <p style={{ fontWeight: 'bold', marginTop: '15px' }}>{this.state.message}</p>
      </div>
    );
  }
}

export default VoterEligibility;

Using arrow functions like handleInputChange = (event) => { … } saves you from writing bind(this) in the constructor.

Conditional Rendering in Class Components

Sometimes you only want to show a piece of the UI if a certain condition is met. In a premium US subscription service, you might only show “Pro Features” to paid users.

Example: Subscription Dashboard

import React, { Component } from 'react';

class SubscriptionStatus extends Component {
  constructor(props) {
    super(props);
    this.state = {
      isPremium: false
    };
  }

  togglePlan = () => {
    this.setState({ isPremium: !this.state.isPremium });
  }

  render() {
    let content;
    if (this.state.isPremium) {
      content = <div style={{ color: 'gold' }}>Welcome to Premium Support (USA Priority Line)</div>;
    } else {
      content = <div style={{ color: 'gray' }}>Standard Plan - Upgrade for faster support.</div>;
    }

    return (
      <div style={{ padding: '20px', border: '1px dashed black' }}>
        <h3>Your Account Status</h3>
        {content}
        <button onClick={this.togglePlan} style={{ marginTop: '10px' }}>
          {this.state.isPremium ? 'Downgrade' : 'Upgrade to Premium'}
        </button>
      </div>
    );
  }
}

export default SubscriptionStatus;

I find this approach using a variable (content) helps keep the return statement clean and readable.

Why Use Class Components Today?

You might wonder why we still learn classes when Hooks are available.

From my experience, many large-scale US legacy systems are built entirely on class components.

If you are hired to maintain an older codebase, you must be comfortable with this syntax.

Additionally, Error Boundaries (a way to catch JS errors in components) can currently only be written as class components.

Learning classes gives you a deeper understanding of how React manages the virtual DOM and component instances.

I hope this guide helps you understand how to implement class-based components in your next React project.

Whether you are building a financial dashboard or a simple profile page, the principles remain the same.

Try creating a few components on your own to get a feel for the state and lifecycle logic.

You may read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.