DeployU
Interviews / Frontend Engineering / This data fetching component is causing an infinite loop. How do you fix it?

Questions

This data fetching component is causing an infinite loop. How do you fix it?

debugging Data Fetching Interactive Quiz Code Examples
Wrong Approach

I'm not sure why it's looping. Maybe debounce the fetch?

Right Approach

The useEffect is missing its dependency array. Without it, the effect runs after every render. Since setItems triggers a re-render, you get an infinite loop:

The Loop:

  1. Component renders
  2. useEffect runs (no dependency array = runs every render)
  3. setItems() updates state → triggers re-render
  4. Back to step 1… forever

The Fix: Add an empty dependency array [] to run the effect only once on mount.

ItemList - Fix the Infinite Loop
Your Code
import React, { useState, useEffect } from 'react';

const fetchItems = () => {
  console.log('Fetching data...');
  return new Promise(resolve => {
    setTimeout(() => resolve(['Item 1', 'Item 2', 'Item 3']), 500);
  });
};

export default function ItemList() {
  const [items, setItems] = useState([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    // THE BUG: Missing dependency array!
    fetchItems().then(data => {
      setItems(data);
      setLoading(false);
    });
  }); // ← Add [] here

  if (loading) return <div>Loading items...</div>;

  return (
    <ul>
      {items.map((item, index) => <li key={index}>{item}</li>)}
    </ul>
  );
}
Click "Run Code" to see output...
Click "Run Code" to see test results...

The Solution

useEffect(() => {
  fetchItems().then(data => {
    setItems(data);
    setLoading(false);
  });
}, []); // Empty array = run once on mount

Dependency Array Rules:

  • [] → Run once on mount (like componentDidMount)
  • [dep1, dep2] → Re-run when dependencies change
  • No array → Run every render (almost never what you want)

Practice Question

What is the purpose of the dependency array in a useEffect hook?