2

useEffect

Run code after rendering and handle cleanup properly

Beginner

Core Concepts

  • useEffect lets you run code AFTER React has updated the screen
  • Use it for side effects (data fetching, subscriptions, timers)
  • The dependency array controls when the effect re-runs
  • Return a cleanup function to remove listeners/timers

Live Demo

0

How It Works

  1. 1
    Component renders with count = 0

    React displays the UI on screen

  2. 2
    AFTER render, useEffect runs

    document.title = "Count: 0"

  3. 3
    User clicks button

    The onClick handler fires

  4. 4
    count becomes 1, component re-renders

    React updates the UI with new count

  5. 5
    AFTER render, useEffect runs again

    document.title = "Count: 1"

Code

import { useState, useEffect } from 'react';

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

  // This runs AFTER every render
  useEffect(() => {
    document.title = `Count: ${count}`; // Update the tab title
  }, [count]); // Only re-run when 'count' changes (This is the dependency array)

  return (
    <div>
      <h1>Counter: {count}</h1>
      <button onClick={() => setCount(count + 1)}>
        Increment (watch the tab title!)
      </button>
    </div>
  );
}

The Dependency Array

The second argument to useEffect is the dependency array. It controls when your effect runs.

// No dependency array (Runs after EVERY render)
useEffect(() => {});

// Empty array (Runs ONCE on mount)
useEffect(() => {}, []);

// With dependencies (Runs when count change)
useEffect(() => {}, [count]);