ReactMedium

How to avoid infinite loops in useEffect?

Infinite loops happen when an effect updates state that is also one of its dependencies (or when there is no dependency array), so each update re-runs the effect. Fix them by listing correct dependencies, avoiding state updates that are not needed, comparing before setting, keeping object and function dependencies stable, and moving derived data out of effects.

Common causes and fixes

  1. No dependency array with setState inside: add the correct array.
  2. Setting a dependency in the effect: useEffect(() => setCount(count + 1), [count]). Ask whether the effect is needed at all; if it computes derived data, calculate during render instead.
  3. Objects or arrays created in render as dependencies: const options = { page } is new every render. Move it inside the effect, depend on primitives, or memoize.
  4. Functions as dependencies: move them into the effect, define them outside the component, wrap in useCallback, or use useEffectEvent for non-reactive logic.
  5. Fetching then storing an object that is a dependency: depend on the ID, not the fetched object.
  6. Parent passes a new callback each render that the child's effect depends on: stabilize it in the parent (or with the React Compiler).

Guards

Only update when something actually changed: if (next !== current) setValue(next).

Tools

  • exhaustive-deps ESLint rule and the React Compiler lint rule set-state-in-effect.
  • React throws "Maximum update depth exceeded" for synchronous loops; check the component stack it prints.
  • React DevTools Profiler shows which value changed on each render.

Code example

tsx
1import { useEffect, useMemo, useState } from "react";
2
3type Item = { id: number; price: number };
4
5export function CartTotal({ items, page }: { items: Item[]; page: number }) {
6 // Bug: loop - effect sets state it depends on
7 // const [total, setTotal] = useState(0);
8 // useEffect(() => { setTotal(items.reduce((s, i) => s + i.price, 0)); }, [items, total]);
9
10 // Fix: derived data needs no effect or state
11 const total = useMemo(() => items.reduce((s, i) => s + i.price, 0), [items]);
12
13 // Bug: new object every render -> effect runs every render
14 // const query = { page, size: 20 };
15 // useEffect(() => { fetchItems(query); }, [query]);
16
17 // Fix: depend on primitives, build objects inside the effect
18 const [rows, setRows] = useState<Item[]>([]);
19 useEffect(() => {
20 let ignore = false;
21 const query = new URLSearchParams({ page: String(page), size: "20" });
22 fetch(`/api/items?${query}`)
23 .then((r) => r.json())
24 .then((data) => !ignore && setRows(data));
25 return () => {
26 ignore = true;
27 };
28 }, [page]);
29
30 return <p>Total: {total} ({rows.length} rows on page {page})</p>;
31}

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the React set.

Open in study app