React Class Components: What They Are and How to Use Them

Last updated 3 months, 2 weeks ago | 313 views 75     5

Tags:- React

Introduction: Why React Class Components Still Matter

While React Hooks and functional components dominate modern React development, class components are still widely used in:

  • Legacy applications

  • Enterprise projects

  • Tutorials and older codebases

Understanding React Class Components is essential for:

  • Maintaining existing code

  • Working on team projects with mixed patterns

  • Learning React’s core concepts like lifecycle methods and state handling

If you're serious about React, you must understand both functional and class components.


What Is a React Class Component?

A class component is an ES6 class that extends from React.Component. It must include a render() method and can manage state and lifecycle methods directly.

import React, { Component } from 'react';

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

Structure of a Class Component

✅ Basic Syntax

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

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

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

⚙️ Key Concepts in Class Components

1. State Management

Use this.state to define and access component state.

this.state = { isVisible: true };         // Initialization
this.setState({ isVisible: false });      // Updating state

2. Props Handling

Access props with this.props.

render() {
  return <h1>Welcome, {this.props.username}</h1>;
}

3. Lifecycle Methods

Lifecycle Phase Method Name Use Case
Mounting componentDidMount() API calls, subscriptions
Updating componentDidUpdate() Respond to prop/state changes
Unmounting componentWillUnmount() Cleanup listeners or intervals

Functional vs Class Component Comparison

Feature Class Component Functional Component
Syntax ES6 class Function
State Management this.state, setState() useState()
Lifecycle Methods Class methods useEffect()
Code Complexity More verbose Concise and readable
Legacy Compatibility ✅ Yes ⚠️ Limited in old React versions

Complete Working Example

// File: App.js
import React, { Component } from 'react';

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

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

  componentDidMount() {
    console.log("Component mounted!");
  }

  componentDidUpdate() {
    console.log("Component updated!");
  }

  componentWillUnmount() {
    console.log("Component will unmount!");
  }

  render() {
    return (
      <div style={{ padding: '1rem', textAlign: 'center' }}>
        <h2>React Class Counter</h2>
        <p>Count: {this.state.count}</p>
        <button onClick={this.increment}>Add</button>
      </div>
    );
  }
}

export default Counter;

Tips & Common Pitfalls

✅ Best Practices

  • Always call super(props) in the constructor.

  • Use arrow functions for methods to preserve this.

  • Group lifecycle logic in respective methods (componentDidMount, etc.).

  • Prefer functional components for new projects, but learn class components for legacy support.

❌ Common Mistakes

  • ❌ Forgetting this. when accessing state or props.

  • ❌ Not binding class methods (if not using arrow functions).

  • ❌ Calling setState in render()—causes infinite loop.

  • ❌ Mutating state directly (this.state.count++) instead of using setState.


Class vs Functional Component Syntax Summary

Feature Class Component Functional Component
Create class X extends Component {} function X() {} or const X = () => {}
Props this.props.name props.name or { name }
State this.state and this.setState() const [state, setState] = useState()
Lifecycle componentDidMount() etc. useEffect(() => {}, [])

Conclusion: Why You Should Still Learn React Class Components

Even though React Hooks are the present and future, class components remain relevant in:

  • Enterprise-grade applications

  • Older codebases

  • Complex integrations

Knowing how to write and read class components makes you a well-rounded React developer capable of working on any project.

Pro Tip: Learn class components to understand the evolution of React and debug legacy code like a pro.


Key Takeaways

  • React Class Components use ES6 classes and support internal state and lifecycle methods.

  • Still widely used in legacy and enterprise codebases.

  • Understanding class components improves your ability to maintain and refactor existing projects.

  • Use arrow functions or bind methods to correctly reference this.