codingstuff.io
ExploreTutorialsProblemsCS Subjects
Get Started
ExploreTutorialsProblemsCS Subjects
Get Started
codingstuff.io

Master the art of building software through interactive tutorials, real-world problems, and guided projects.

Pune, Maharashtra, India

codingstuffmail@gmail.com

Product

  • Explore
  • Tutorials
  • Problems
  • CS Subjects

Company

  • About
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Sitemap

© 2026 codingstuff.io. All rights reserved.

Built with ❤️ for developers everywhere

/
/
All Tutorials
⚛️

React.js

6 / 61 topics
1Introduction to React.js2Setting Up Your Development Environment3JSX: Basics and Syntax4Components Introduction5Functional Components6Class Components7Props: Introduction and Usage8State: Introduction and Usage9Event Handling in React
Tutorials/React.js/Class Components
⚛️React.js

Class Components

Updated 2026-04-20
3 min read

Class Components

Introduction

React.js is a powerful JavaScript library for building user interfaces, and understanding its core concepts is crucial for effective development. One of the fundamental ways to create components in React is through class components. This tutorial will provide a comprehensive guide on how to use class components effectively in your React applications.

What are Class Components?

Class components in React are ES6 classes that extend from React.Component. They allow you to utilize additional features such as state and lifecycle methods, which are not available in functional components (prior to React 16.8).

Basic Structure

A basic class component looks like this:

import React, { Component } from 'react';

class MyComponent extends Component {
  render() {
    return <div>Hello, World!</div>;
  }
}

export default MyComponent;

In this example:

  • MyComponent is a class that extends React.Component.
  • The render() method returns the JSX to be rendered.

State in Class Components

State is an object that holds information about the component. It can change over time, and when it changes, the component re-renders.

Initializing State

You initialize state in the constructor of your class:

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

  render() {
    return <div>Count: {this.state.count}</div>;
  }
}

Updating State

To update the state, use the setState method:

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

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

  render() {
    return (
      <div>
        Count: {this.state.count}
        <button onClick={this.incrementCount}>Increment</button>
      </div>
    );
  }
}

Best Practices for State Management

  • Avoid Direct Mutation: Always use setState to update the state. Directly mutating this.state can lead to unpredictable behavior.
  • State Immutability: Treat state as immutable. When updating, create a new object or array based on the previous state.

Lifecycle Methods

Class components provide lifecycle methods that allow you to run code at specific points in your component's lifecycle. These are particularly useful for fetching data, setting up subscriptions, and cleaning up resources.

Common Lifecycle Methods

  • componentDidMount(): Called after the component is rendered for the first time.
  • componentDidUpdate(prevProps, prevState): Called after updates to props or state.
  • componentWillUnmount(): Called right before a component is removed from the DOM.

Example: Fetching Data

class DataFetcher extends Component {
  constructor(props) {
    super(props);
    this.state = {
      data: null,
    };
  }

  componentDidMount() {
    fetch('https://api.example.com/data')
      .then(response => response.json())
      .then(data => this.setState({ data }));
  }

  render() {
    return (
      <div>
        {this.state.data ? (
          <pre>{JSON.stringify(this.state.data, null, 2)}</pre>
        ) : (
          'Loading...'
        )}
      </div>
    );
  }
}

Best Practices for Lifecycle Methods

  • Avoid Side Effects in Render: Do not perform side effects like data fetching or subscriptions inside the render method.
  • Cleanup Resources: Always clean up resources (e.g., event listeners, timers) in componentWillUnmount.

Handling Events

Class components handle events similarly to functional components. You define methods on your class and bind them to event handlers.

Binding Methods

You can bind methods in the constructor or use arrow functions for concise syntax:

class MyComponent extends Component {
  constructor(props) {
    super(props);
    this.state = { count: 0 };
    // Binding method in constructor
    this.incrementCount = this.incrementCount.bind(this);
  }

  incrementCount() {
    this.setState({ count: this.state.count + 1 });
  }

  render() {
    return (
      <div>
        Count: {this.state.count}
        {/* Using bound method */}
        <button onClick={this.incrementCount}>Increment</button>
      </div>
    );
  }
}

// Alternatively, using arrow functions
class MyComponent extends Component {
  constructor(props) {
    super(props);
    this.state = { count: 0 };
  }

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

  render() {
    return (
      <div>
        Count: {this.state.count}
        {/* Using arrow function */}
        <button onClick={this.incrementCount}>Increment</button>
      </div>
    );
  }
}

Best Practices for Event Handling

  • Use Arrow Functions: They automatically bind this, making your code cleaner and less error-prone.
  • Avoid Inline Binding: Binding methods inline can lead to performance issues, especially in lists.

Context in Class Components

Context allows you to pass data through the component tree without having to pass props down manually at every level. In class components, you use contextType or a higher-order component (HOC) like withContext.

Using contextType

class MyComponent extends Component {
  static contextType = ThemeContext;

  render() {
    return <div>Current theme: {this.context}</div>;
  }
}

Best Practices for Context

  • Limit Context Usage: Overusing context can make your components harder to understand and maintain.
  • Avoid Deep Nesting: Use context sparingly, especially in deeply nested component trees.

Conclusion

Class components are a powerful feature of React.js that provide state management and lifecycle methods. While functional components with hooks have become the preferred way for many developers due to their simplicity and reusability, understanding class components is still valuable, especially when working with older codebases or needing access to certain features like error boundaries.

By following best practices for state management, event handling, and context usage, you can create robust and maintainable React applications using class components.


PreviousFunctional ComponentsNext Props: Introduction and Usage

Recommended Gear

Functional ComponentsProps: Introduction and Usage