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
- No dependency array with
setStateinside: add the correct array. - 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. - 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. - Functions as dependencies: move them into the effect, define them outside the component, wrap in
useCallback, or useuseEffectEventfor non-reactive logic. - Fetching then storing an object that is a dependency: depend on the ID, not the fetched object.
- 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-depsESLint rule and the React Compiler lint ruleset-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";23type Item = { id: number; price: number };45export function CartTotal({ items, page }: { items: Item[]; page: number }) {6 // Bug: loop - effect sets state it depends on7 // const [total, setTotal] = useState(0);8 // useEffect(() => { setTotal(items.reduce((s, i) => s + i.price, 0)); }, [items, total]);910 // Fix: derived data needs no effect or state11 const total = useMemo(() => items.reduce((s, i) => s + i.price, 0), [items]);1213 // Bug: new object every render -> effect runs every render14 // const query = { page, size: 20 };15 // useEffect(() => { fetchItems(query); }, [query]);1617 // Fix: depend on primitives, build objects inside the effect18 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]);2930 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.