React Mastery / React Hooks

useEffect with Incorrect Dependency

⚠️ useEffect with Incorrect Dependency

  • The dependency array tells React when to re-run an effect.

  • If dependencies are missing or incorrect, your effect may:

    • Use stale (old) values

    • Not run when it should

    • Run too many times

    • Cause bugs or infinite loops


❌ Missing Dependency Example

useEffect(() => {
  console.log(count);
}, []); // ❌ count is missing

🔴 Problem:

  • Effect runs only once

  • count value never updates inside effect

✅ Correct Version

useEffect(() => {
  console.log(count);
}, [count]);

✔️ Effect runs whenever count changes

❌ Too Many Dependencies

useEffect(() => {
  fetchData();
}, [count]); // ❌ fetchData doesn't depend on count

🔴 Problem:

  • Unnecessary re-runs

❌ Infinite Loop Example

useEffect(() => {
  setCount(count + 1);
}, [count]); // ❌ infinite updates

🧠 Rule of Thumb

Every state or prop used inside useEffect must be listed in the dependency array.


🔁 Class Component Comparison

Class Component

useEffect

prevState checks

Dependency array


🔚 In Short

  • Missing dependency → stale data

  • Extra dependency → unnecessary runs

  • Wrong dependency → bugs or loops

✔️ Always keep dependency array accurate