Maximum update depth exceeded

React JavaScript Library

Severity: Moderate

What it means

React's error: Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops. (#185)
Newer versions also say: This could be an infinite loop. This can happen when a component repeatedly calls setState during render phase or inside useLayoutEffect.
And as a warning: 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.

Affected Models

  • React 16.8 and later

How to Fix It

  1. A useEffect that sets state and has no dependency array? It runs after every render, and each set causes another render. Add the array, listing what the effect reads.

  2. A dependency that's new on every render, such as an object, an array or a function made in the component body? React's docs: move it inside the effect, or outside the component.

  3. Setting state from its own previous value? Use the updater form, setCount(c => c + 1), and leave count out of the dependencies.

  4. A class component? In componentDidUpdate, compare before setting: if (prevProps.id !== this.props.id) and only then this.setState().