Skip to Content
Module 5: Side Effects & Hooks5.1 Component Lifecycle

Module 5.1: Component Lifecycle & useEffect

An illustration showing a timeline with "Mounting," "Updating," and "Unmounting" stages of a React component, with useEffect connecting to each stage.

🎯 What You’ll Learn

After this module, you’ll master:

  • Component Lifecycle: Understand the three core stages: Mount, Update, and Unmount.
  • useEffect Hook: Your primary tool for managing side effects within Function Components.
  • Dependency Array: How to control when useEffect runs to prevent infinite loops.
  • Cleanup Function: How to prevent memory leaks when a component is destroyed.

1. The Component Lifecycle

Just like humans, every component in React goes through three main stages. Understanding these three stages (and their internal phases) is key to gaining control over your application.

A detailed diagram illustrating the lifecycle methods and hooks of a React component, from mounting to unmounting, showing render and commit phases.

1.1. The Three Stages

  1. Mounting (Birth):
    • This happens when the component is first added to the DOM.
    • Process: Initialize state -> Render UI -> Update DOM -> Run Side Effects (useEffect).
  2. Updating (Change):
    • Occurs when props change, state changes, or the parent component re-renders.
    • Process: Re-render UI -> Compare diff -> Update DOM -> Re-run Side Effects.
  3. Unmounting (Death):
    • When the component is removed from the DOM.
    • Process: Perform cleanup for Side Effects to prevent memory leaks.

1.2. The Two Processing Phases

React divides its processing into two distinct phases:

  • Render Phase (Calculation):

    • React runs your function component.
    • This phase must be “Pure” (no side effects, no API calls, no direct DOM mutations).
    • It only calculates what the UI should look like.
  • Commit Phase (Execution):

    • React actually modifies the DOM (adds nodes, updates text).
    • Once the DOM updates are complete, React then runs Side Effects (useEffect).
    • This is the safe place to make API calls, interact with the DOM, or set setTimeout.

For more details, see the Lifecycle Diagram

2. Basic useEffect Hook

A simplified diagram showing the useEffect hook, its callback function, and the dependency array, highlighting its role in managing side effects.

In Function Components, we use useEffect to handle Side Effects (ancillary tasks) at different points in the component’s lifecycle.

2.1. Syntax

useEffect(() => { // Code to run here (Effect) return () => { // Cleanup code (Optional) }; }, [dependencies]); // Dependency array

2.2. Common Use Cases

StageDependency Array []Description
Mount Only[] (Empty)Runs only once after the initial render. Commonly used for API calls, event setup.
Update[prop, state]Runs once initially AND whenever a variable in the array changes.
Every Render(Omitted)Runs after every render. ⚠️ Use sparingly, as it can cause performance issues.
Unmountreturn () => {}The cleanup function runs before the component disappears.

3. Diving Deeper into Each Stage

3.1. Mounting (Run Once)

Use an empty dependency array [].

import { useEffect } from 'react'; function Welcome() { useEffect(() => { console.log('✅ Component has appeared (Mounted)'); // Example: Fetch user information via API // fetchUser(); }, []); // <--- Important: Empty array return <h1>Hello World</h1>; }

3.2. Updating (Tracking Variables)

Runs when the count variable changes.

function Counter() { const [count, setCount] = useState<number>(0); useEffect(() => { console.log(`🔄 Count has changed to: ${count}`); document.title = `Count: ${count}`; // Update the web page title }, [count]); // <--- Re-runs when 'count' changes return <button onClick={() => setCount(count + 1)}>+</button>; }

3.3. Unmounting (Cleanup)

Use the return function inside useEffect. This is a critically important step to prevent Memory Leaks.

Example: If you setInterval (set a timer) but don’t clear it when the component unmounts, the timer will continue running in the background indefinitely.

function Timer() { useEffect(() => { const timerId = setInterval(() => { console.log('⏰ Tick tack...'); }, 1000); // CLEANUP FUNCTION return () => { console.log('🗑️ Cleaning up timer'); clearInterval(timerId); // Clear the interval }; }, []); return <div>Timer is running...</div>; }

4. Hands-on Labs

Lab 1: Lifecycle Console Dashboard

Instead of hidden console.log messages in Developer Tools, let’s build a “Visual Logger” directly into the interface.

  • A toggle button to Mount/Unmount the child component.
  • An area to display event logs: “Born”, “Updated”, “Died” with different colors.

A screenshot of a web application with a toggle button to show or hide a child component, and a log display area showing "Born," "Updated," and "Died" events.

💡 Hint:

  • Use useEffect with [] to log when the component Mounts.
  • Use the return function of useEffect to log when the component Unmounts.
  • Use props callbacks to send logs from the child to the parent and store them in the logs state (array).

Lab 2: Retro Digital Timer (Neon Style)

Create a countdown timer with a Cyberpunk/Retro style.

  • Display hours : minutes : seconds.
  • Neon Glow effect.
  • Ensure no Memory Leaks when hiding the clock.

A screenshot of a digital clock styled with a retro neon glow, displaying hours, minutes, and seconds.

💡 Hint:

  • Use setInterval inside useEffect to update the time every second.
  • IMPORTANT: You must call clearInterval in the cleanup function. Otherwise, when the clock is hidden, the timer will still run in the background, causing errors or consuming resources.
  • Use new Date().toLocaleTimeString() to get the current time string.

5. Summary

  1. Mount ([]): Use for data setup, API calls, and event listener registration.
  2. Update ([deps]): Use to react to state/props changes (e.g., Autosave, Sync).
  3. Unmount (cleanup): Use to clearInterval, removeEventListener, and cancel requests.
  4. Always remember: If you create anything that runs in the background (Intervals, Listeners), you MUST clean it up in the cleanup function.

6. References

Last updated on