Course contentsShow
← React
Lesson 571 of 2,39616. useEffect for Data FetchingFree lesson

The Empty Dependency Array Pattern

Use [] to fetch data once on mount, understanding when this is appropriate and when it causes problems.

The Empty Dependency Array Pattern

What you'll learn: How to use an empty dependency array ([]) to fetch data exactly once when a component mounts, and when this pattern is appropriate.

The Core Idea

When you provide an empty array as the second argument to useEffect, React runs that effect only once — right after the component first appears on screen (mounts). It won't run again on re-renders, even if props or state change.

useEffect(() => {
  fetch('/api/user')
    .then(res => res.json())
    .then(data => setUser(data))
    .catch(err => setError(err));
}, []); // Empty array means "no dependencies"

This tells React: "This effect depends on nothing, so run it once and never again."

When This Pattern Works

The empty array pattern is perfect for initial data loading that shouldn't repeat:

  • Fetching user profile data on page load
  • Loading app configuration that doesn't change
  • Initializing third-party libraries once

Think of it like ordering groceries when you move into a new apartment — you do it once to stock up, not every time you walk through the door.

When This Pattern Causes Problems

If your fetch logic references props or state, an empty array creates stale closure bugs:

// BAD: searchTerm is missing from dependencies
useEffect(() => {
  fetch(`/api/search?q=${searchTerm}`)
    .then(res => res.json())
    .then(data => setResults(data));
}, []); // Won't re-fetch when searchTerm changes!

The ESLint rule will warn you about this. You must include searchTerm in the array, or your effect uses the old value forever.

Key Takeaway: Use an empty dependency array [] only when your effect truly needs to run once on mount and references no changing values. Missing dependencies create bugs where your effect uses stale data.