Mid From PDF React React.js

How do you avoid infinite loops with useEffect?

Short answer: Infinite loops in useEffect occur when the effect continually triggers itself because the dependency array includes values that change as a result of the effect itself.

Explain a bit more

Common cause: If a value inside useEffect is being updated, and it's in the dependency array, React will keep rerunning the effect. How to avoid: Use an empty dependency array ([]) if the effect should run only once. Be selective with dependencies to avoid unnecessary re-renders.

Example code

useEffect(() => { // Perform API call or other side effects fetchData(); }, []); // No dependencies, effect runs only once If the dependency list has state values or props that change inside the effect, React will rerun it every time those values change. Be mindful of that!

Real-world example (ShopNest)

ShopNest’s cart icon uses useState for count and useEffect to load the cart once on mount.

Say this in the interview

  1. Define — one clear sentence (the short answer above).
  2. Example — relate it to a project like ShopNest or your real work.
  3. Trade-off — when you would not use it.
Toolliyo Assistant
Ask about tutorials, ebooks, training, pricing, mentor services, and support. I use public site content only—not admin or internal tools.

care@toolliyo.com

Need callback? Share your details