Class Components: State and Lifecycle

Dive into the core of classic React by mastering state management and lifecycle methods in class components.

📄

Welcome! Let's build a React class component from scratch to see how it works.

/* App.js - Empty */

The Class Component Blueprint

Class components are JavaScript classes that extend React.Component. They must have a render() method that returns JSX. This is the basic blueprint for a stateful, dynamic part of your UI.

Introducing 'state': The Component's Memory

The state is a private object where a component can store data that might change over time. It's initialized in the constructor() method. Think of it as the component's internal memory.

Updating State with `this.setState`

To change the state, you must call this.setState(). This function tells React that the state has changed, and it will trigger a re-render of the component to reflect the new data. You should never modify this.state directly.

The Component Lifecycle: Mount & Update

Lifecycle methods are special functions that run at specific points in a component's life. componentDidMount() runs after the component is added to the DOM (great for API calls), and componentDidUpdate() runs after it re-renders.

Practice Zone


Interactive Test 1: Sort the Methods

Drag the lifecycle methods and constructor into their correct places in the class component.

Arrastra en el orden correspondiente.


Arrastra las opciones:

constructor
componentDidMount
componentDidUpdate
render

Completa el código:

class MyComponent extends Component { ______(props) { super(props); this.state = { data: null }; }
______() { console.log('Mounted!'); }
______() { console.log('Updated!'); }
______() { return <div>Hello</div>; } }
Unlock with Premium

Interactive Test 2: Manage the State

Rellena los huecos en cada casilla.

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

  increment = () => {
    this.({ count: this.state.count + 1 });
  }
}
Unlock with Premium

Practice Example: Code Editor

Build a simple class component that displays a message in its state and has a button to change it.

* Write the code below. Correct characters will be shown in green and incorrect ones in red.

import React, { Component } from 'react'; class Message extends Component { constructor(props) { super(props); this.state = { message: 'Hello, World!' }; } updateMessage = () => { this.setState({ message: 'Hello, React!' }); } render() { return ( <div> <h1>{this.state.message}</h1> <button onClick={this.updateMessage}>Change Message</button> </div> ); } } export default Message;
Unlock with Premium

Knowledge Check

Which method is used to update the state in a class component?


Unlock with Premium

The Lifecycle in Practice

Lifecycle methods are not just theoretical; they are essential for building real-world applications. Here are common use cases.


1. Fetching Data on Mount

componentDidMount is the perfect place to fetch data from an API. It runs only once after the component is in the DOM, so you can safely update the state with the fetched data.

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

2. Reacting to Prop Changes

componentDidUpdate receives the previous props and state as arguments. You can compare this.props with prevProps to perform actions only when specific data has changed, avoiding unnecessary operations.

componentDidUpdate(prevProps) {
  // Refetch data if the user ID prop changes
  if (this.props.userID !== prevProps.userID) {
    this.fetchUserData(this.props.userID);
  }
}

3. Cleaning Up Before Unmount

If you set up any subscriptions or timers in componentDidMount, you must clean them up in componentWillUnmount to prevent memory leaks when the component is removed from the screen.

componentWillUnmount() {
  clearInterval(this.intervalID);
  this.unsubscribeFromService();
}

Practical Takeaway: Understanding the lifecycle lets you control your component's behavior precisely, managing side effects like data fetching and subscriptions efficiently.

React Class Glossary

React.Component
The base class you extend to create a React class component.
constructor(props)
The class constructor. It's used to call `super(props)` and initialize `this.state`.
state
A built-in object that stores property values belonging to the component. When the state object changes, the component re-renders.
setState()
A method that schedules an update to a component's state object. It triggers a UI re-render.
render()
The only required method in a class component. It examines `this.props` and `this.state` and returns JSX to be rendered to the DOM.
componentDidMount()
A lifecycle method that runs after the component has been rendered to the DOM. Ideal for API calls or setting up subscriptions.
componentDidUpdate()
Runs immediately after updating occurs (e.g., after `setState`). Not called for the initial render.
componentWillUnmount()
Invoked immediately before a component is unmounted and destroyed. Used for cleanup tasks.