⚛️ React useEffect Hook

Chapter 12 of 15

What is useEffect?

The useEffect Hook allows you to perform side effects in your components. Side effects are operations that affect something outside the component, such as:

💡 Think of useEffect as: componentDidMount, componentDidUpdate, and componentWillUnmount combined!

Basic Syntax

import { useEffect } from "react";

useEffect(function, dependencies)

Example 1: Run on Every Render

If you don't provide a dependency array, useEffect runs after every render:

import { useState, useEffect } from "react";

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

  useEffect(() => {
    setTimeout(() => {
      setCount((count) => count + 1);
    }, 1000);
  });

  return <h1>I've rendered {count} times!</h1>;
}

Example 2: Run Once (on Mount)

Pass an empty array [] to run the effect only once:

import { useState, useEffect } from "react";

function DataFetcher() {
  const [data, setData] = useState(null);

  useEffect(() => {
    fetch('https://api.example.com/data')
      .then(response => response.json())
      .then(data => setData(data));
  }, []); // Empty array = run once

  return <div>{data ? data.title : "Loading..."}</div>;
}
✨ Common Pattern: Empty dependency array [] is perfect for fetching data when component mounts!

Example 3: Run When Dependencies Change

Specify dependencies to run the effect only when those values change:

import { useState, useEffect } from "react";

function Counter() {
  const [count, setCount] = useState(0);
  const [calculation, setCalculation] = useState(0);

  useEffect(() => {
    setCalculation(() => count * 2);
  }, [count]); // Only re-run when count changes

  return (
    <>
      <p>Count: {count}</p>
      <button onClick={() => setCount((c) => c + 1)}>+</button>
      <p>Calculation: {calculation}</p>
    </>
  );
}

Effect Cleanup

Return a cleanup function to clean up resources when the component unmounts or before the effect runs again:

import { useState, useEffect } from "react";

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

  useEffect(() => {
    let timer = setTimeout(() => {
      setCount((count) => count + 1);
    }, 1000);

    // Cleanup function
    return () => clearTimeout(timer);
  }, []);

  return <h1>I've rendered {count} times!</h1>;
}
⚠️ Important: Always cleanup subscriptions, timers, and event listeners to prevent memory leaks!

Common Use Cases

1. Fetching Data

useEffect(() => {
  const fetchData = async () => {
    const response = await fetch('api/url');
    const data = await response.json();
    setData(data);
  };
  
  fetchData();
}, []);

2. Setting up Event Listeners

useEffect(() => {
  const handleResize = () => {
    setWindowWidth(window.innerWidth);
  };
  
  window.addEventListener('resize', handleResize);
  
  // Cleanup
  return () => {
    window.removeEventListener('resize', handleResize);
  };
}, []);

3. Document Title Update

useEffect(() => {
  document.title = `You clicked ${count} times`;
}, [count]);

4. Local Storage

useEffect(() => {
  localStorage.setItem('count', count);
}, [count]);

Multiple useEffect Hooks

You can use multiple useEffect hooks in a single component for different concerns:

function MyComponent() {
  const [count, setCount] = useState(0);
  const [name, setName] = useState("");

  // Effect for count
  useEffect(() => {
    document.title = `Count: ${count}`;
  }, [count]);

  // Effect for name
  useEffect(() => {
    console.log(`Name changed to: ${name}`);
  }, [name]);

  // Effect that runs once
  useEffect(() => {
    console.log("Component mounted");
  }, []);
  
  // ...
}

Dependency Array Rules

Dependencies When Effect Runs
No array After every render
Empty array [] Only once (on mount)
[var1, var2] When var1 or var2 changes

Best Practices

⚠️ Common Mistake:
// ❌ Wrong - infinite loop
useEffect(() => {
  setCount(count + 1);
});

// ✅ Correct
useEffect(() => {
  setCount(count + 1);
}, []); // Only run once

What's Next?

Now that you understand useEffect, you're ready to learn about useContext for managing global state!