How to Fix useEffect Infinite Loop in React
useEffect happens when its dependency array changes on every render, causing repeated effect runs. To fix it, ensure the dependency array only includes stable values or variables that should trigger the effect, and avoid updating state inside useEffect without proper conditions.Why This Happens
An infinite loop in useEffect occurs when the effect updates a state or a value that is also listed in its dependency array. This causes React to rerun the effect continuously because the dependency changes every time the effect runs.
For example, if you update a state inside useEffect without limiting when it runs, React keeps triggering the effect again and again.
import React, { useState, useEffect } from 'react'; function InfiniteLoopExample() { const [count, setCount] = useState(0); useEffect(() => { setCount(count + 1); // Updates state every render }, [count]); // count is a dependency return <div>Count: {count}</div>; }
The Fix
To fix the infinite loop, avoid updating state inside useEffect without a proper condition or remove the state variable from the dependency array if safe. Often, you want to run the effect only once by passing an empty dependency array [], or include only necessary dependencies that do not change every render.
In the example, remove count from dependencies and use a functional update to avoid stale state.
import React, { useState, useEffect } from 'react'; function FixedExample() { const [count, setCount] = useState(0); useEffect(() => { setCount(prevCount => prevCount + 1); // Update once on mount }, []); // Empty array runs effect only once return <div>Count: {count}</div>; }
Prevention
To avoid infinite loops in useEffect:
- Only include necessary dependencies in the dependency array.
- Use functional updates when updating state inside
useEffect. - Use conditions inside
useEffectto prevent unwanted state updates. - Use ESLint plugin
eslint-plugin-react-hooksto get warnings about missing or extra dependencies. - Understand when to use an empty dependency array
[]to run effect only once.
Related Errors
Other common errors related to useEffect include:
- Missing dependencies: Forgetting to add variables to the dependency array can cause stale data.
- Excessive re-renders: Caused by updating state in
useEffectwithout conditions. - Memory leaks: Not cleaning up subscriptions or timers inside
useEffect.
Quick fixes include carefully managing dependencies and cleanup functions.