React · Chapter 13 of 42

useEffect Hook

`useEffect` lets you run side effects in function components — things like data fetching, subscriptions, or manually changing the DOM, after render.

The effect runs after the component renders. You can control when it re-runs using a dependency array.

Dependency array

An empty array `[]` runs the effect once after mount. Omitting the array runs it after every render. Listing values re-runs the effect when they change.

Cleanup

Return a cleanup function from the effect to clean up subscriptions, timers, or listeners before the next effect run or unmount.

Example 1 (jsx)
import { useState, useEffect } from "react";

function Timer() {
  const [seconds, setSeconds] = useState(0);

  useEffect(() => {
    const id = setInterval(() => setSeconds(s => s + 1), 1000);
    return () => clearInterval(id);
  }, []);

  return <p>Seconds: {seconds}</p>;
}
Output
Seconds: 0, 1, 2, ...

The effect starts a timer once, and cleans it up on unmount.

Key points

  • useEffect runs side effects after rendering.
  • The dependency array controls when the effect re-runs.
  • Return a cleanup function to avoid memory leaks.
  • Empty array [] means 'run once, on mount'.
💡 Note: Forgetting the dependency array is a common source of infinite effect loops.

📝 Quick Quiz

1. When does an effect with an empty dependency array run?

2. What does the cleanup function do?

3. What kind of tasks belong in useEffect?