How do you avoid infinite loops with useEffect?
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.
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:
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!