Unit 2: State Management & HooksLesson #4 / 5

Lesson 4: Side Effects & The useEffect Hook

Er. Manoj Kumar — AuthorEr. Manoj KumarLast Updated: 26 Aug, 2026

1. Managing Side Effects with useEffect

Side effects include API data fetching, setting timers, subscribing to event listeners, and updating local storage.

  • Mount Only ([] dependency array): Runs once on component mount.
  • State/Prop Triggered ([count, user]): Runs when specified dependencies change.
  • Cleanup Function: Returning a function from useEffect runs cleanup before re-running or when unmounting (clearing intervals, event listeners).
  • Code Example
    import React, { useState, useEffect } from 'react';
    export default function UserDataFetcher() {
    const [data, setData] = useState(null);
    const [loading, setLoading] = useState(true);
    useEffect(() => {
    // 1. Fetching API data on mount
    let isMounted = true;
    fetch('https://api.github.com/users/manoj2403')
    .then(res => res.json())
    .then(json => {
    if (isMounted) {
    setData(json);
    setLoading(false);
    }
    });
    // 2. Cleanup on unmount
    return () => { isMounted = false; };
    }, []); // Runs once on mount
    if (loading) return <div>Loading developer profile...</div>;
    return <div>Loaded: {data?.name || "Developer"}</div>;
    }

    Interactive Knowledge Check

    Test your understanding of Lesson #4 concepts

    When does a useEffect with an empty dependency array [] execute?