Web Unit 3 Sprint 9 - Class Components & Testing

Module 1: Class Components

In this module, you'll learn about class components in React and how they differ from functional components. You'll understand the lifecycle methods and state management in class components.

Class components have been a significant part of the React ecosystem because they provide functionality that wasn't initially available with functional components. Though hooks now bring similar capabilities to functional components, many existing projects still use class components, making it essential to understand how to work with them.

The focus will be on understanding React's Component base class, which allows access to lifecycle methods, state management, and event handling in a class-based approach.

Learning Objectives

  • Explain class components and use a class component to render some state data to the DOM
  • Describe the three phases of the React component lifecycle
  • Properly explain what the constructor and render methods do and what their place is in the React component lifecycle
  • Simulate interactions with userEvent

Remember the "CCR" approach to building class components:

  1. Class - Declare your class and extend React.Component
  2. Constructor - Set up state and bind methods
  3. Render/Return - Render UI to the DOM

Content

Introduction to Class Components

Class components are ES6 classes that extend React.Component. They were the primary way to manage state and lifecycle methods before the introduction of hooks.

A basic class component looks like this:

import React from 'react';

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

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

export default MyComponent;
                    

Key Concepts

The Class Structure

  • Extends React.Component: Inherits functionality from React's Component class
  • Constructor: Initialize state and bind methods
  • this.state: The component's local state object
  • this.props: Properties passed from parent components
  • this.setState(): Method to update state (triggers re-render)
  • render(): Required method to return JSX

State in Class Components

Managing State

Class components manage state through the constructor and setState method:

  • Initialize state in constructor
  • Access state with this.state
  • Update state with this.setState()
  • Never modify this.state directly

setState() Deep Dive

setState() has several important characteristics:

  • It's asynchronous
  • It performs shallow merges
  • It can accept a function for state updates that depend on previous state
  • It can accept a callback function as a second argument

Additional Resources