react
runtime_error
ai_generated
true
Error: Maximum update depth exceeded. This can happen when a component calls setState inside useEffect, but useEffect either doesn't have a dependency array, or one of the dependencies changes on every render.
ID: react/state-update-in-effect-without-deps
88%Fix Rate
90%Confidence
1Evidence
2023-08-22First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| React 18.2.0 | active | — | — | — |
| React 17.0.2 | active | — | — | — |
Root Cause
A useEffect with a state update either lacks a dependency array (runs after every render) or has a dependency that mutates on every render (e.g., a new object/function), causing an infinite loop.
generic中文
带有状态更新的 useEffect 要么缺少依赖数组(每次渲染后运行),要么有一个在每次渲染时都会发生变化的依赖(例如新的对象/函数),从而导致无限循环。
Official Documentation
https://react.dev/reference/react/useEffect#updating-state-based-on-previous-stateWorkarounds
-
95% success Provide a proper dependency array with stable values. If the state update depends on previous state, use the functional update form: setState(prev => prev + 1).
Provide a proper dependency array with stable values. If the state update depends on previous state, use the functional update form: setState(prev => prev + 1).
-
90% success If the effect needs to react to a changing value, ensure that value is memoized with useMemo or useCallback to maintain referential stability.
If the effect needs to react to a changing value, ensure that value is memoized with useMemo or useCallback to maintain referential stability.
中文步骤
Provide a proper dependency array with stable values. If the state update depends on previous state, use the functional update form: setState(prev => prev + 1).
If the effect needs to react to a changing value, ensure that value is memoized with useMemo or useCallback to maintain referential stability.
Dead Ends
Common approaches that don't work:
-
50% fail
If the effect needs to react to prop or state changes, an empty array makes it run only once, potentially missing updates and causing stale data.
-
85% fail
Inline functions/objects are new references each render, so the effect runs every time, defeating the purpose.