React

Too Many Re-renders in React - Why & How to Fix

Understanding and fixing "Too many re-renders. React limits the number of renders" error. Learn about common causes and solutions.

6 min read
ReactPerformanceuseStateuseEffect

The Error

Too many re-renders. React limits the number of renders to prevent an infinite loop.

Common Causes

1. Setting State Directly in Render

// ❌ Wrong - Causes infinite loop
function Component() {
  const [count, setCount] = useState(0)
  setCount(count + 1) // Called every render!
  return <div>{count}</div>
}

// ✅ Correct - Use event handler
function Component() {
  const [count, setCount] = useState(0)

  const increment = () => {
    setCount(count + 1)
  }

  return <button onClick={increment}>{count}</button>
}

2. Incorrect Event Handler Syntax

// ❌ Wrong - Calls function immediately
<button onClick={handleClick()}>Click</button>

// ✅ Correct - Pass function reference
<button onClick={handleClick}>Click</button>

// ✅ Also correct - Use arrow function
<button onClick={() => handleClick()}>Click</button>

3. useEffect Missing Dependencies

// ❌ Wrong - Updates state in useEffect with no deps
useEffect(() => {
  setData(fetchData())
}) // Runs on every render!

// ✅ Correct - Add empty dependency array
useEffect(() => {
  setData(fetchData())
}, []) // Runs once on mount

// ✅ Correct - Include all dependencies
useEffect(() => {
  if (userId) {
    setData(fetchUserData(userId))
  }
}, [userId]) // Runs when userId changes

4. State Update in Render causing Re-render

// ❌ Wrong
function Component({ data }) {
  const [processed, setProcessed] = useState(null)

  if (data) {
    setProcessed(processData(data)) // Infinite loop!
  }

  return <div>{processed}</div>
}

// ✅ Correct - Use useEffect
function Component({ data }) {
  const [processed, setProcessed] = useState(null)

  useEffect(() => {
    if (data) {
      setProcessed(processData(data))
    }
  }, [data])

  return <div>{processed}</div>
}

Quick Debug Tips

  • Check if you're calling functions in onClick instead of passing them
  • Look for setState calls outside of event handlers or useEffect
  • Verify useEffect dependencies are correct
  • Check if parent component is re-rendering unnecessarily
  • Use React DevTools Profiler to identify the source

Prevention

Always set state in response to events (clicks, form submissions) or in useEffect hooks. Never call setState directly in the component body during render.

Frustration Level Before Finding This Fix

How frustrated were you? Vote and see what others experienced!

Share this article

Share:
K

Kushagra Kukreti

Full-Stack Developer specializing in React, Next.js, and TypeScript. Sharing short, crisp solutions to common development issues.