What is the Dependency Array?
You'll learn how the second argument to useEffect controls when your effect re-runs—preventing unnecessary executions and fixing infinite loops.
The Problem: Effects Run After Every Render
By default, useEffect runs after every render. If your effect updates state, that triggers another render, which runs the effect again—creating an infinite loop. Even without loops, running expensive operations (like API calls) on every render wastes resources.
The Dependency Array: Your Control Mechanism
The dependency array is the optional second argument to useEffect:
useEffect(() => {
// Your effect code
}, [dependency1, dependency2]);
This array tells React: "Only re-run this effect if one of these values has changed since the last render."
How It Works
React compares each value in the array to its previous value (using Object.is). If any value changed, the effect runs. If all values are identical to last time, React skips the effect entirely.
const [count, setCount] = useState(0);
const [name, setName] = useState('');
useEffect(() => {
document.title = `Count: ${count}`;
}, [count]); // Only runs when count changes, not when name changes
Three Patterns
- No array: Effect runs after every render (default behavior)
- Empty array
[]: Effect runs only once, after the initial render - Array with values: Effect runs when any listed value changes
Key Takeaway: The dependency array is your way of telling React "I only want this effect to run when these specific values change"—it's essential for controlling effect execution and preventing performance problems.