REACT Class Components

Class components were the primary way to define components in React before the introduction of Hooks in functional components. Although functional components are now preferred, class components are still used in many projects, especially older ones.

1. What Are Class Components?

A class component is a React component defined using an ES6 class. It extends the React.Component base class and must include a render() method, which returns the JSX representing the UI.

2. Syntax of Class Components

Basic Class Component

import React, { Component } from 'react';

class Welcome extends Component {
    render() {
        return <h1>Welcome to React!</h1>;
    }
}

export default Welcome;

Try It Now

3. Key Features of Class Components

  1. State Management: Class components have a built-in state object for managing local state.
  2. Lifecycle Methods: Class components support lifecycle methods like componentDidMount, componentDidUpdate, and componentWillUnmount.
  3. Props Handling: Class components receive props as an implicit property.

4. State in Class Components

The state object allows you to manage component-specific data that can change over time.

Using State

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 });
    };

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

export default Counter;

Try It Now

5. Lifecycle Methods in Class Components

Class components provide lifecycle methods to handle component initialization, updates, and unmounting.

Common Lifecycle Methods

  1. componentDidMount(): Invoked after the component is mounted to the DOM.
  2. componentDidUpdate(prevProps, prevState): Called after updates to props or state.
  3. componentWillUnmount(): Called just before the component is removed from the DOM.

Example Using Lifecycle Methods

import React, { Component } from 'react';

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

    componentDidMount() {
        this.timerID = setInterval(() => {
            this.setState({ time: this.state.time + 1 });
        }, 1000);
    }

    componentWillUnmount() {
        clearInterval(this.timerID);
    }

    render() {
        return <p>Time: {this.state.time} seconds</p>;
    }
}

export default Timer;

Try It Now

6. Props in Class Components

Props are passed to class components just like functional components. They can be accessed using this.props.

Example Using Props

import React, { Component } from 'react';

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

// Usage
<Greeting name="John" />;

Try It Now

7. Event Handling in Class Components

Class components handle events by defining methods and binding them to this if necessary.

Example: Event Handling

import React, { Component } from 'react';

class ClickMe extends Component {
    handleClick() {
        alert('Button clicked!');
    }

    render() {
        return <button onClick={this.handleClick}>Click Me</button>;
    }
}

export default ClickMe;

Try It Now

8. Comparison: Functional vs. Class Components

Feature Class Components Functional Components
Syntax ES6 class JavaScript function
State Management this.state useState Hook
Lifecycle Methods Explicit (componentDidMount, etc.) useEffect Hook
Performance Slightly slower due to lifecycle overhead Faster with Hooks
Code Complexity More boilerplate Minimal and modern syntax

9. Best Practices for Class Components

  1. Use constructor only when you need to initialize state or bind methods.
  2. Avoid deep nesting of components to maintain readability.
  3. Use setState instead of directly modifying the state object.
  4. Optimize performance with lifecycle methods like shouldComponentUpdate.

10. Example: Complete Class Component

import React, { Component } from 'react';

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

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

    componentDidMount() {
        console.log('Component Mounted');
    }

    componentDidUpdate(prevProps, prevState) {
        if (prevState.count !== this.state.count) {
            console.log(`Count updated: ${this.state.count}`);
        }
    }

    componentWillUnmount() {
        console.log('Component Unmounted');
    }

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

export default App;

Try It Now

11. When to Use Class Components

  • Legacy Projects: Many older React projects are built with class components.
  • Working with Third-Party Libraries: Some libraries or tools may still rely on class components.

However, for new projects, it’s recommended to use functional components with Hooks due to their simplicity and modern capabilities.

Conclusion

Class components are an important part of React’s history, offering state and lifecycle features before Hooks were introduced. While functional components are now the standard, understanding class components helps developers work with legacy React codebases and deepen their knowledge of React’s evolution.