Error Encyclopedia

React Too Many Re-renders Error

Fix 'Too many re-renders' error in React. Learn how state updates cause infinite loops and how to use useEffect correctly.

What Does This Error Mean?

The 'Too many re-renders' error occurs when a component enters an infinite render loop. React limits re-renders to prevent browser crashes. This typically happens when setState is called directly in the render body, triggering an immediate re-render that calls setState again.

Common Causes

1

Calling setState directly in the component body (not in an event handler or useEffect)

2

State update in useEffect without proper dependency array

3

Inline event handler that calls setState during render

4

Custom hook that updates state on every render

5

Parent component re-rendering causing child to re-render, triggering state update

How to Fix It

Move state updates to event handlers

Never call setState directly in the component body.

function Counter() {
  const [count, setCount] = useState(0)
  
  // ❌ Direct call in render body causes infinite loop
  setCount(count + 1) // DON'T DO THIS
  
  // ✅ Call in event handler
  return <button onClick={() => setCount(c => c + 1)}>{count}</button>
}

Use useEffect for side effects

Move state updates that depend on other state changes into useEffect.

function SearchResults({ query }) {
  const [results, setResults] = useState([])
  const [loading, setLoading] = useState(false)
  
  // ✅ Side effects go in useEffect
  useEffect(() => {
    if (!query) return
    setLoading(true)
    fetch(`/api/search?q=${query}`)
      .then(res => res.json())
      .then(data => {
        setResults(data)
        setLoading(false)
      })
  }, [query]) // ✅ Only runs when query changes
  
  return <div>...</div>
}

Use functional state updates

When updating state based on previous state, use the functional form.

const [count, setCount] = useState(0)

// ❌ Might cause issues if called rapidly
setCount(count + 1)

// ✅ Functional form is safer
setCount(prev => prev + 1)

Related Tools

Use these tools to debug and fix this error:

Related Errors

Other common errors in this category: