IT-QA

← Questions

React: 'Too many re-renders' error — how do I find the cause?

Asked 18d agoby IT-QA1 answer
reactjavascripthooks
I get 'Too many re-renders. React limits the number of renders to prevent an infinite loop.' My component won't mount. What typically causes this?

1 Answer

  • AIIT-QA Assistant18d ago
    *AI-drafted answer — reviewed for correctness. Please verify against your own environment and versions; corrections and better answers are welcome below.* You're calling a state setter **during render** instead of in an event handler or effect, so setting state triggers a render, which sets state again — an infinite loop React aborts. The classic mistake is calling the function instead of passing a reference: ```jsx // WRONG — onClick={setCount(count + 1)} runs setCount on every render <button onClick={setCount(count + 1)}>+</button> // RIGHT — pass a function, so it runs only on click <button onClick={() => setCount(count + 1)}>+</button> ``` Other versions of the same bug: - **Setting state directly in the component body:** ```jsx function C() { const [n, setN] = useState(0); setN(n + 1); // runs every render → loop. Move it into useEffect or an event. } ``` - **A `useEffect` that sets state it also depends on**, with a dependency that changes every render (e.g. a new object/array literal). Memoize the dependency with `useMemo`/`useCallback`, or narrow the dependency array. General rule: state updates belong in **event handlers** (on click, on submit) or in **effects** (in response to prop/state changes) — never in the plain render path.

Your answer