Course contentsShow
← React
Lesson 624 of 2,39617. Common useEffect MistakesFree lesson

Object Dependencies Causing Loops

How passing new object literals or array literals in dependencies triggers infinite re-runs.

Object Dependencies Causing Loops

What you'll learn: Why passing object or array literals directly into a useEffect dependency array triggers endless re-renders.


The Core Problem

Remember that objects and arrays are compared by reference, not by value. When you write { userId: 5 } or [1, 2, 3] directly in your JSX or component body, JavaScript creates a brand new object every render—even if the contents are identical.

If you pass that object into your useEffect dependencies, React sees a "different" object each time, thinks the dependency changed, runs your effect, which triggers a re-render, which creates another new object, which triggers the effect again... infinite loop.

Common Trap

function UserProfile({ userId }) {
  const [data, setData] = useState(null);

  useEffect(() => {
    fetch(`/api/user/${userId}`)
      .then(res => res.json())
      .then(setData);
  }, [{ userId }]); // 🔴 New object every render = infinite loop

  return <div>{data?.name}</div>;
}

Every render creates a fresh { userId } object. React compares the old object reference to the new one, sees they're different (even though userId hasn't changed), and runs the effect. The effect calls setData, causing a re-render, which creates another new object... and so on forever.

The Fix

Use primitive values directly in the dependency array:

useEffect(() => {
  fetch(`/api/user/${userId}`)
    .then(res => res.json())
    .then(setData);
}, [userId]); // ✅ Primitive value, compared by value

Key Takeaway: Never pass object or array literals directly into the dependency array—extract the primitive values you actually care about, or React will see a "new" dependency every single render.