在 React 中使用 useEffect 时,为什么有时候会出现无限循环?
Author: 图恩Category: 编程开发Views: 96Published: 2025-10-31 **Why Does an Infinite Loop Occur When Using useEffect in React?**
**Answer and Explanation:**
In React, the `useEffect` hook is designed to handle side effects such as data fetching, subscriptions, or DOM manipulations. An infinite loop often arises when the dependency array (dependency list) is improperly managed.
**Common Causes:**
1. **Updating the state within `useEffect` while the state itself is included in the dependency array, and each update generates a new reference.**
Example:
```jsx
function MyComponent() {
const [data, setData] = useState([]);
useEffect(() => {
setData([...data, 'new item']); // New array is created each time
}, [data]); // `data` is the dependency
}
```
Each call to `setData` triggers a re-render, creating a new `data` reference. The `useEffect` hook re-executes, leading to an infinite loop.
2. **Using objects or functions in the dependency array, which are re-created on each render.**
Example:
```jsx
useEffect(() => {
fetchData();
}, [{ a: 1 }]); // New object is created each render
```
The `useEffect` hook is triggered repeatedly due to the re-creation of the dependency.
**Solutions:**
- **Use functional updates** to avoid relying on the state itself:
```jsx
useEffect(() => {
setData(prev => [...prev, 'new item']);
}, []); // No dependency needed
```
- **For object/function dependencies**, use `useMemo`, `useCallback`, or move them outside the component (e.g., define them in a separate file or use `useRef` to retain stable references).
- **Review the dependency array** to ensure only values that actually need to change are included.
**Summary:**
The root cause of an infinite loop in `useEffect` is when dependencies change after each render, triggering state updates that re-trigger the effect, creating a loop. Properly managing dependencies and state updates is critical to avoiding this issue.