Developments

The useEffect Infinite Loop & How to Fix It

Efraim Ray Efraim Ray 0 Comments
Developer Notes & Solution

In this developer note, we break down the useEffect infinite loop — the single most common hooks bug new (and not-so-new) React developers run into — trace exactly why it happens, and walk through the fix along with the habits that keep it from coming back.

Environment React 18+ / JavaScript
Scope / Type Debugging Guide
Time to Fix ~15 min
Affected Stack React Hooks
Severity Medium (Perf / UX)
React code editor on screen
Engineering Workbench

The Problem & Root Cause Analysis

The tab freezes. The fan spins up. React DevTools shows the same component rendering hundreds of times a second. Eventually the console fills with a warning every React developer eventually meets face to face:

The Symptom

A component re-renders continuously with no user interaction. CPU usage spikes, the UI becomes unresponsive, and React eventually throws a "Maximum update depth exceeded" warning before the tab locks up entirely.

The Root Cause

A useEffect calls setState unconditionally, and one of its dependencies — usually an object, array, or function — gets a brand-new reference on every render, so the effect re-fires forever.

console • browser devtools
Warning: Maximum update depth exceeded. This can happen when a component calls setState inside useEffect, but useEffect either doesn't have a dependency array, or one of the dependencies changes on every render. --> at SearchResults (SearchResults.jsx:14:3) (React will keep re-rendering until the call stack overflows)

Before vs. After: The Code Fix

Here's the exact pattern that causes it — an options object recreated on every render, handed straight to useEffect's dependency array — next to the fix:

BEFORE (Infinite Loop) SearchResults.jsx
// ❌ Flawed: a new object every render
function SearchResults({ query }) {
  const [results, setResults] = useState([]);

  // New object reference on every single render!
  const options = { query, limit: 20 };

  useEffect(() => {
    fetchResults(options).then(setResults);
  }, [options]); // 🔁 "options" is never === last time

  return <ResultsList items={results} />;
}
AFTER (Stable Dependencies) SearchResults.jsx
// ✅ Fixed: depend on primitives, not objects
function SearchResults({ query }) {
  const [results, setResults] = useState([]);

  useEffect(() => {
    const options = { query, limit: 20 };
    fetchResults(options).then(setResults);
  }, [query]); // ✅ "query" is a primitive string

  return <ResultsList items={results} />;
}

Complete Implementation: A Reusable Debounced Fetch Hook

Moving the object inside the effect fixes this one case, but the sturdier long-term fix is pulling the pattern into a custom hook so the dependency rules only have to be gotten right once:

import { useState, useEffect } from 'react';

// Reusable hook: debounces a value and fetches on change.
// Depends only on primitives (query, delayMs) — never an
// object or function recreated on every render.
export function useDebouncedFetch(query, delayMs = 300) {
  const [data, setData] = useState([]);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    if (!query) {
      setData([]);
      return;
    }

    setLoading(true);
    const timer = setTimeout(() => {
      fetchResults({ query, limit: 20 })
        .then(setData)
        .finally(() => setLoading(false));
    }, delayMs);

    // Cleanup: cancel the pending fetch if query changes again
    return () => clearTimeout(timer);
  }, [query, delayMs]);

  return { data, loading };
}
import { useState } from 'react';
import { useDebouncedFetch } from './useDebouncedFetch';

function SearchResults() {
  const [query, setQuery] = useState('');
  const { data, loading } = useDebouncedFetch(query);

  return (
    <>
      <input
        value={query}
        onChange={(e) => setQuery(e.target.value)}
        placeholder="Search..."
      />
      {loading ? <Spinner /> : <ResultsList items={data} />}
    </>
  );
}
{
  "extends": ["react-app"],
  "plugins": ["react-hooks"],
  "rules": {
    "react-hooks/rules-of-hooks": "error",
    "react-hooks/exhaustive-deps": "warn"
  }
}

Step-by-Step Debugging Workflow

When a component won't stop rendering, work through these steps in order rather than guessing at the fix:

1

Step 1: Confirm It's useEffect

Open React DevTools' Profiler and record a render. If one component re-renders dozens of times with no prop changes, the cause is almost always a setState call inside an effect.

2

Step 2: Read the Dependency Array Literally

For every value in the array, ask: "does this get a new reference every render?" Objects, arrays, and inline functions almost always do unless they're memoized.

3

Step 3: Depend on Primitives, Not Objects

Move object/array construction inside the effect, or destructure the primitive fields you actually need and list those instead.

4

Step 4: Turn On exhaustive-deps

Enable the react-hooks/exhaustive-deps ESLint rule so the compiler — not production users — catches the next one.

Common useEffect Pitfalls & How to Spot Them

The object-dependency loop above is the most common version, but it's not the only one. These show up just as often:

Easy to Miss
Missing Dependency Array Entirely

A useEffect with no second argument runs after every render. If it also calls setState, that's an unconditional infinite loop by itself.

Quick Fix
Inline Functions Passed as Props

An inline onClick={() => doThing()} passed to a memoized child defeats React.memo — wrap it in useCallback if it's also a dependency somewhere downstream.

Good Habit
Prefer Functional setState Updates

setCount(c => c + 1) doesn't need count in the dependency array at all — often the simplest way to shrink a dependency list is to not need the value in the first place.

Terminal Cheatsheet & Diagnostic Commands

Handy one-liners for catching this class of bug before it ships:

$npx eslint src/ --rule '{"react-hooks/exhaustive-deps":"error"}'
$npm install --save-dev eslint-plugin-react-hooks
$npm run build -- --profile

Render Flow & Profiling Visuals

React DevTools profiler dashboard
Profiling

Spotting the Loop in React DevTools

Hundreds of commits with no prop changes is the telltale sign.

Code architecture diagram on a whiteboard
Architecture

Render → Effect → setState → Render

The cycle that repeats forever once a dependency never stabilizes.

Code editor workspace
Tooling

ESLint Catching It Before Runtime

exhaustive-deps turns a runtime crash into a lint warning.

Developer Pro-Tip

If you find yourself reaching for useMemo or useCallback just to stabilize a dependency, first ask whether that value needs to be a dependency at all. Removing the need is almost always simpler than memoizing around it.

Source Code, Docs & Discussion

GitHub Profile

See more hooks patterns and project source on GitHub.

View on GitHub

Official React Docs

The official reference on useEffect, dependency arrays, and the rules of hooks.

Read Docs

Developer Discussions

Hit a useEffect bug that doesn't fit this pattern? Get in touch.

Ask a Question
Developer Takeaway

Stable Dependencies, Stable Components

The useEffect infinite loop isn't really a React bug — it's a reference-equality bug wearing a React costume. Depend on primitives, memoize deliberately instead of defensively, and let ESLint catch the rest.

Efraim Ray
Written by

Efraim Ray

Software Developer and AI Specialist. BS Information Technology graduate. I pride myself on being conscientious, attentive to detail, and always open to learning — because the best solutions come from listening, taking notes, and exploring what's next.

Comments