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

Functions in Dependencies: The Problem

Functions created in render have new references each time, causing effects to re-run unnecessarily.

Functions in Dependencies: The Problem

What you'll learn: Why putting functions in a useEffect dependency array often causes infinite loops or unnecessary re-runs.

The Core Issue

When you define a function inside your component body, React creates a brand new function object on every single render. Even if the function does the exact same thing, its reference changes each time.

Now imagine you put that function in your useEffect dependency array. React compares dependencies by reference (like objects and arrays). Since the function is "new" every render, React thinks it changed—so your effect runs again. That effect might trigger a state update, causing another render, creating another new function... and you've got an infinite loop.

A Mental Model

Think of it like this: You have a recipe card (the function) that says "make pancakes." Every morning, you rewrite the recipe on a fresh card—same words, same instructions. But your kitchen assistant (React) sees a different card and thinks, "Oh, new recipe! Better make pancakes again!" even though nothing actually changed.

The Classic Mistake

function MyComponent({ userId }) {
  const fetchUser = () => {
    fetch(`/api/users/${userId}`).then(/* ... */);
  };

  useEffect(() => {
    fetchUser();
  }, [fetchUser]); // ⚠️ fetchUser is new every render!
}

The fetchUser function gets recreated on every render. The effect sees a "different" function and runs again, potentially causing performance issues or infinite loops if it triggers state updates.

Key Takeaway: Functions created during render have fresh references each time, making them problematic dependencies—React sees them as constantly changing even when their behavior hasn't.