Learning navigation

Code with Animation

The Dependency Array

How to control exactly when your side effects re-run by explicitly declaring their dependencies.

React4 min readConcept 14 of 48

What it is

The dependency array is the optional second argument to useEffect (and useMemo/useCallback).

It is an array containing all the reactive values (props, state, and local variables) that your effect uses inside its body.

Why it matters

By default, an effect runs after every single render. This is usually bad for performance, especially if it fetches data or manipulates the DOM.

The dependency array allows you to tell React: 'Only run this effect again if one of these specific values has changed since the last render.'

The three configurations

1. No array: useEffect(() => {...}) Runs after every render.

2. Empty array: useEffect(() => {...}, []) Runs only once after the initial render (on mount).

3. Populated array: useEffect(() => {...}, [x, y]) Runs on mount, and re-runs only if x or y changes.

The Three Forms

Click the buttons to trigger a component re-render. Watch how the three different forms of useEffect react to the changing state.

const [a, setA] = useState(0);
const [b, setB] = useState(0);
 
// 1. No Array (Runs on EVERY render)
useEffect(() => {
log('Effect 1 ran');
});
 
// 2. Empty Array (Runs ONCE on mount)
useEffect(() => {
log('Effect 2 ran');
}, []);
 
// 3. Populated Array (Runs when 'A' changes)
useEffect(() => {
log('Effect 3 ran');
}, [a]);
Both buttons trigger a full component re-render.
Effect Execution Logs

Click the buttons to trigger renders. Notice how Effect 1 always fires, Effect 2 never fires after the initial load, and Effect 3 only fires when A changes.

Check yourself

Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.

  1. 1What happens if you pass an empty array `[]` as the second argument to `useEffect`?
  2. 2You use a state variable `count` inside your effect, but pass an empty dependency array `[]`. What will happen?
  3. 3When should you completely omit the dependency array (e.g., `useEffect(() => { ... })`)?

Remember this

  • No array: runs after every render.
  • Empty array []: runs once on mount.
  • Array with values [x, y]: runs when x or y changes.
  • If a value is used inside the effect, it must go in the array (don't lie to React).

Done with this concept?

Mark it complete to track your progress. No login needed.