The dependency array tells React when to run some code again. It helps avoid running code too many times or missing updates.
Dependency array usage in React
useEffect(() => {
// code to run
}, [dependency1, dependency2]);The array at the end is called the dependency array.
React runs the code inside useEffect only if one of the dependencies changes.
useEffect(() => {
console.log('Runs once when component mounts');
}, []);count value changes.useEffect(() => {
console.log('Runs when count changes:', count);
}, [count]);useEffect(() => {
console.log('Runs every render because no array');
});user or theme changes.useEffect(() => {
console.log('Runs when user or theme changes');
}, [user, theme]);This component shows how dependency arrays control when effects run:
- The first effect runs only once when the component appears.
- The second effect runs only when
countchanges. - The third effect runs only when
namechanges.
Try clicking the button or typing in the input to see console logs.
import React, { useState, useEffect } from 'react'; function Counter() { const [count, setCount] = useState(0); const [name, setName] = useState(''); useEffect(() => { console.log('Component mounted'); }, []); useEffect(() => { console.log(`Count changed to: ${count}`); }, [count]); useEffect(() => { console.log(`Name changed to: ${name}`); }, [name]); return ( <div> <p>Count: {count}</p> <button onClick={() => setCount(count + 1)}>Increase Count</button> <p>Name: {name}</p> <input type="text" value={name} onChange={e => setName(e.target.value)} aria-label="Name input" /> </div> ); } export default Counter;
Time complexity: Effects run only when dependencies change, so efficient updates.
Space complexity: Minimal, just stores dependencies internally.
Common mistake: Forgetting to add dependencies causes effects to not update when expected.
Use dependency arrays to control when side effects run and avoid unnecessary work.
The dependency array controls when React runs your effect code.
Empty array means run once; no array means run every render.
Always list all variables your effect uses in the dependency array.