Course contentsShow
← React
Lesson 539 of 2,39615. useEffect FundamentalsFree lesson

Array with Values: Run When Dependencies Change

Learn how listing values in the array makes the effect re-run only when those specific values change.

Array with Values: Run When Dependencies Change

What you'll learn: How to control exactly when your effect re-runs by listing specific values in the dependency array.


When you pass an array with values to useEffect, React will only re-run that effect if one or more of those values has changed since the last render. This gives you precise control over effect execution.

How It Works

useEffect(() => {
  console.log(`User ID changed to: ${userId}`);
  // Fetch user data, subscribe to updates, etc.
}, [userId]); // Only runs when userId changes

React compares each value in the array to its previous value (using Object.is equality). If any value is different, the effect runs again. If all values are the same, React skips the effect entirely.

Multiple Dependencies

You can list multiple values:

useEffect(() => {
  document.title = `${name} - Page ${currentPage}`;
}, [name, currentPage]); // Runs when EITHER changes

The effect re-runs when any dependency changes, not just all of them together.

The Mental Model

Think of the dependency array as your "watch list" — you're telling React: "Only re-synchronize this effect when these specific pieces of data change." It's like setting up alerts for specific stock prices instead of checking the entire market constantly.

What to Include

Include every value from props, state, or context that your effect uses. If your effect references userId, put userId in the array. Omitting dependencies leads to stale data bugs.

// ❌ BAD: Missing dependency
useEffect(() => {
  console.log(count); // Uses count but doesn't list it
}, []);

// ✅ GOOD: All dependencies listed
useEffect(() => {
  console.log(count);
}, [count]);

Key Takeaway: The dependency array with values lets you run effects only when specific data changes, giving you precise control over synchronization while avoiding unnecessary re-runs.