← Lessons

quiz vs the machine

Gold1460

Frontend

The useEffect Dependency Array

Why the dependency list decides when an effect re runs.

5 min read · core · beat Gold to climb

Synchronizing with the outside

useEffect runs side effects after render, like subscriptions, timers, and data fetching. The dependency array tells React when to run the effect again.

How the array behaves

  • No array means the effect runs after every render.
  • An empty array means it runs once after mount.
  • A list of values means it re runs whenever one of them changes by reference or value.

React compares dependencies between renders. If you read a prop or state inside the effect, it belongs in the array, or the effect will use a stale value captured from an old render.

Cleanup

An effect can return a cleanup function. React runs it before the next effect and on unmount, which is how you remove listeners and clear timers to avoid leaks.

The lint rule

The dependencies linter flags missing values. Resist the urge to silence it. Instead make values stable with useCallback or move them inside the effect.

Key idea

The dependency array controls when an effect re runs, so include every value the effect reads and return a cleanup to avoid stale closures and leaks.

Check yourself

Answer to earn rating on the learn ladder.

1. What does an empty dependency array mean?

2. What happens if you omit a value the effect reads?

3. What is the cleanup function for?