The dependency array in useEffect determines when the effect runs or re-runs in a React component.
⚙️ 1. No Dependency Array
useEffect(() => {
console.log("Runs after every render");
});
🔸 The effect runs after every render (both initial and updates).
⚙️ 2. Empty Dependency Array []
useEffect(() => {
console.log("Runs only once");
}, []);
🔸 The effect runs only once — after the initial render, like componentDidMount.
⚙️ 3. With Dependencies
useEffect(() => {
console.log("Runs when count changes");
}, [count]);
🔸 The effect runs only when the specified dependencies (count here) change.
⚙️ 4. Cleanup Function
If your effect returns a function, React runs that cleanup before re-running the effect or when the component unmounts.
useEffect(() => {
const timer = setInterval(() => console.log("Tick"), 1000);
return () => clearInterval(timer); // Cleanup
}, [count]);
💡 In Short:
The dependency array controls when and how often
useEffectexecutes —
✅ Empty[]→ Run once
✅ With deps[x, y]→ Run when x or y changes
✅ Without array → Run after every render