Skip to main content

Command Palette

Search for a command to run...

18) Component Lifecycle

Updated
View as Markdown
  1. Functional Component Lifecycle Phases
    In modern React, functional components don’t have lifecycle methods like class components. Instead, lifecycle behavior is handled using hooks, mainly useEffect.
    Even in functional components, the lifecycle still conceptually has 3 phases,
    i) Mounting (Component created)
    ii) Updating (State/props change)
    iii) Unmounting (Component removed)

    In React functional component the useEffect hook is use as a Lifecycle Controller.
    The useEffect hook replaces,
    i) componentDidMount
    ii) componentDidUpdate
    iii) componentWillUnmount
    Depending on how you use it, it behaves differently.

  2. Lifecycle Mapping with Examples
    i) Mounting Phase (componentDidMount)
    Runs only once when component mounts
    It is equivalent to componentDidMount()

    import { useEffect } from "react";
    
    const App = () => {
      useEffect(() => {
        console.log("Component Mounted");
      }, []); // empty dependency array, runs only once
    
      return <h1>Hello World</h1>;
    }
    

    ii) Updating Phase (componentDidUpdate)
    Runs when dependency changes
    It is equivalent to componentDidUpdate(prevProps, prevState)

    import { useState, useEffect } from "react";
    
    const Counter = () => {
      const [count, setCount] = useState(0);
    
      useEffect(() => {
        console.log("Count Updated:", count);
      }, [count]); // runs only when count changes
    
      return (
        <button onClick={() => setCount(count + 1)}>
          Count: {count}
        </button>
      );
    }
    

    iii) Unmounting Phase (componentWillUnmount)
    It uses Cleanup function
    It is equivalent to componentWillUnmount()

    import { useEffect } from "react";
    
    const Timer = () => {
      useEffect(() => {
        const interval = setInterval(() => {
          console.log("Running...");
        }, 1000);
    
        return () => {
          clearInterval(interval);
          console.log("Component Unmounted");
        };
      }, []);
    
      return <h1>Timer Running</h1>;
    }