← Back to Chapters

React Component Lifecycle

⚛️ React Component Lifecycle

? Quick Overview

Every React component goes through a sequence of stages during its existence — from creation to removal. These stages are collectively known as the Component Lifecycle.

Understanding the lifecycle helps you handle side effects, fetch data, clean up subscriptions, and optimize performance.

? Key Lifecycle Phases

A React component passes through three main lifecycle phases:

  • Mounting — The component is created and inserted into the DOM.
  • Updating — The component re-renders when its state or props change.
  • Unmounting — The component is removed from the DOM.

?️ Class Component Lifecycle Methods

In class components, React provides dedicated lifecycle methods that are called at specific moments:

  • Mounting: constructor(), componentDidMount()
  • Updating: componentDidUpdate()
  • Unmounting: componentWillUnmount()
? View Code Example
// Class component lifecycle demo (mount, update, unmount)
import React, { Component } from "react";

class LifecycleDemo extends Component {
  constructor() {
    super();
    this.state = { count: 0 };
    console.log("Constructor - Mounting");
  }

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

  componentDidUpdate() {
    console.log("Component Updated");
  }

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

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

?️ What Happens Here?

  • On first render (mount): the constructor runs, then componentDidMount() logs "Component Mounted".
  • When you click "Increment": state changes, React re-renders, and componentDidUpdate() logs "Component Updated".
  • When the component is removed: componentWillUnmount() runs and logs "Component Unmounted", which is the right place to perform cleanup.

⚙️ Lifecycle in Functional Components (Hooks)

Functional components don’t have lifecycle methods. Instead, they use the useEffect() hook to perform lifecycle-like actions.

? View Code Example
// Functional component lifecycle demo using useEffect
import { useState, useEffect } from "react";

function LifecycleDemo() {
  const [count, setCount] = useState(0);

  // Mounting + Updating
  useEffect(() => {
    console.log("Component Mounted or Updated");
  });

  // Mounting only (runs once)
  useEffect(() => {
    console.log("Component Mounted");
  }, []);

  // Unmounting (cleanup)
  useEffect(() => {
    return () => {
      console.log("Component Unmounted");
    };
  }, []);

  return (
    <div>
      <h3>Count: {count}</h3>
      <button onClick={() => setCount(count + 1)}>
        Increment
      </button>
    </div>
  );
}

export default LifecycleDemo;

? Mapping useEffect to Lifecycle Phases

  • useEffect(callback) → runs after every render (mount + update) like componentDidMount + componentDidUpdate.
  • useEffect(callback, []) → runs only once after the first render like componentDidMount.
  • useEffect(() => return cleanup, []) → the cleanup function runs when the component unmounts, similar to componentWillUnmount.

? Lifecycle Summary: Class vs Functional

This table shows how class lifecycle methods map to useEffect in functional components:

Phase Class Component Functional Component
Mounting componentDidMount() useEffect(callback, [])
Updating componentDidUpdate() useEffect(callback)
Unmounting componentWillUnmount() return cleanup inside useEffect()

? Real-world Use Cases

  • ? Mounting: Fetch API data when the component first loads (e.g., user profile, product list).
  • ? Updating: Re-run calculations or sync data when props or state change (e.g., filtering a list).
  • ? Unmounting: Clean up event listeners, intervals, WebSocket connections, or subscriptions.

? Tips & Best Practices

  • Use cleanup functions in useEffect to avoid memory leaks when components unmount.
  • Use dependency arrays carefully — missing dependencies can cause stale data or unexpected behavior.
  • Always clean up timers, intervals, and event listeners in componentWillUnmount or the useEffect cleanup.
  • Use multiple useEffect hooks for different concerns (e.g., one for fetching, one for subscriptions).

? Try It Yourself

  1. Create a component that fetches and displays data from an API on mount using useEffect(..., []).
  2. Add a button that triggers an update (e.g., reload the data or change a filter) and observe re-renders.
  3. Log lifecycle messages for mount, update, and unmount phases (using console.log inside effects).
  4. Conditionally render the component and verify that your cleanup code runs when it unmounts.

Goal: Understand how React manages component lifecycle phases — Mounting, Updating, and Unmounting — and how to handle side effects properly using lifecycle methods or hooks.