D Dev Notebook

React Component Lifecycle

Component Lifecycle

The component lifecycle in React describes the stages a React component goes through from creation to removal in the browser. You can think of it like the life of a person:

  • Born (Mounting) — the component is created & inserted into the DOM.
  • Grows / Changes (Updating) — whenever it receives new props or its state changes, it updates.
  • Dies (Unmounting) — it gets removed from the DOM, and cleanup happens.

The 3 main phases:

1. Mounting

This is when the component first gets created & rendered on the screen. In class components:

  • constructor
  • render
  • componentDidMount

2. Updating

Whenever props or state change, the component re-renders. In class components:

  • render
  • componentDidUpdate

3. Unmounting

When the component is removed from the screen / DOM. In class components:

  • componentWillUnmount

Example:

import React, { useState, useEffect } from 'react';

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

  console.log('🎨 render');

  // Equivalent of componentDidMount
  useEffect(() => {
    console.log('✅ componentDidMount (mounted)');

    // Equivalent of componentWillUnmount
    return () => {
      console.log('❌ componentWillUnmount (cleanup)');
    };
  }, []); // empty dependency array → runs once on mount

  // Equivalent of componentDidUpdate
  useEffect(() => {
    if (count !== 0) {
      console.log('🔄 componentDidUpdate (updated)');
    }
  }, [count]); // runs when `count` changes

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

export default Example;

What happens when?

Mounting (first time component appears on screen):

  • constructor ➡️ render ➡️ componentDidMount

Updating (after setState or new props):

  • render ➡️ componentDidUpdate

Unmounting (component removed from DOM):

  • componentWillUnmount

functional components (with hooks)

The useEffect hook is used to handle side-effects during mounting, updating, and unmounting.

useEffect(() => {
  console.log("mounted or updated");

  return () => {
    console.log("cleanup before unmount or before next effect");
  }
}, [dependencies]);

On this page