Category: Next.js, React and TypeScript

React: Maximum Update Depth Exceeded in useEffect

Read this guide in Polish

Once the CPU page is opened, the component renders itself in the loop and a maximum update depth error appears. The effect changes the state on which it depends, or each time it receives a new object of dependence.

How to determine the source of the error

Check the list of defendencies useEffect and any setState function called inside the effect.

With the help of the render counter, determine whether the default is a new object, array or callback in each render.

What to do step by step

1. Remove the redundant condition if the value can be calculated during rendering; otherwise limit the update to the actual change.

2 . Stabilize the required references with useMemo or use callback only if it solves a specific cause.

How to check the score

The number of renders stabilizes and the change of input data continues to update the view as expected.

What to do

Do not add empty [] without analysis, because you can freeze the needed syncs.