CPCODELAB
React

useEffect and the Dependency Array

12 min read

Synchronising with the Outside World

useEffect lets you run side effects — code that interacts with things outside React's control: browser APIs, timers, subscriptions, and network requests. It runs after React has painted the DOM.

jsx
import { useState, useEffect } from 'react';

function DocumentTitle({ title }) {
  useEffect(() => {
    document.title = title;
  }, [title]); // Re-run whenever title changes

  return <h1>{title}</h1>;
}

The dependency array

  • No array — effect runs after every render.
  • Empty array `[]` — effect runs once after the first render (mount).
  • Array with values `[a, b]` — effect runs when a or b change.

Always include every reactive value used inside the effect in the dependency array. Omitting dependencies causes stale-closure bugs that are notoriously hard to debug.

Ready to test yourself?
Practice React— quiz & coding exercises