⚛️ React Q6 / 113

What are class components?

AI-Powered Answer ✓ Answered

Class components are one of the two primary ways to define components in React (the other being functional components). They are ES6 classes that extend from `React.Component` and have the ability to manage their own state and lifecycle methods, making them suitable for more complex UI logic before the introduction of React Hooks.

Definition and Structure

A class component is a JavaScript class that inherits from React.Component. It must include a render() method that returns JSX, which describes the UI to be rendered. Class components can also hold local state and define various lifecycle methods.

Basic Example

jsx
import React from 'react';

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

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

  render() {
    return (
      <div>
        <h1>Hello, {this.props.name}!</h1>
        <p>Count: {this.state.count}</p>
        <button onClick={this.incrementCount}>Increment</button>
      </div>
    );
  }
}

export default MyClassComponent;

Key Characteristics

  • State (this.state): Class components can have internal state, which is an object that holds data that might change over the component's lifetime. State is initialized in the constructor and updated using this.setState().
  • Lifecycle Methods: They provide special methods that are invoked at different stages of a component's lifecycle (e.g., when it's mounted, updated, or unmounted). These methods allow developers to perform side effects, data fetching, or cleanup operations.
  • Props (this.props): Data passed from a parent component to a class component is accessible via this.props. Props are read-only and should not be directly modified within the component.
  • render() Method: This is the only required method in a class component. It returns a React element (JSX) that describes what should be rendered to the DOM.
  • this Context: Unlike functional components, class components rely heavily on the this keyword to access state, props, and methods. Care must be taken to correctly bind this for event handlers.

Common Lifecycle Methods

  • constructor(props): Called before the component is mounted. Used for initializing local state and binding event handler methods.
  • static getDerivedStateFromProps(props, state): Invoked right before calling the render method, both on the initial mount and on subsequent updates. It should return an object to update the state, or null to update nothing.
  • componentDidMount(): Invoked immediately after a component is mounted (inserted into the DOM tree). Ideal for data fetching, subscriptions, or DOM manipulations that require the component to be rendered.
  • shouldComponentUpdate(nextProps, nextState): Allows you to control whether a component should re-render or not. Returns true by default, but can be overridden for performance optimizations.
  • componentDidUpdate(prevProps, prevState, snapshot): Invoked immediately after updating occurs. Useful for performing side effects when props or state change, but not on the initial render.
  • componentWillUnmount(): Invoked immediately before a component is unmounted and destroyed. Used for cleanup tasks such as invalidating timers, canceling network requests, or unsubscribing from events.

Functional Components vs. Class Components

While class components were the standard for stateful logic and lifecycle management, the introduction of React Hooks in version 16.8 provided functional components with the ability to manage state (useState) and side effects (useEffect), making them capable of handling virtually everything class components could. As a result, functional components with Hooks are generally preferred for new development due to their simpler syntax, better readability, and easier testing.

However, class components are still valid React components and are widely used in existing codebases. Understanding them is crucial for working with legacy projects or for appreciating the evolution of React.