The Dependency Array
How to control exactly when your side effects re-run by explicitly declaring their dependencies.
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.
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.
Remember this
- No array: runs after every render.
- Empty array
[]: runs once on mount. - Array with values
[x, y]: runs whenxorychanges. - 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.