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

Moving Functions Inside Effects

If a function is only used in one effect, define it inside the effect to avoid dependency issues.

Moving Functions Inside Effects

What you'll learn: How to eliminate function dependency problems by defining helper functions directly inside your useEffect.


The Simplest Solution to Function Dependencies

You've learned that putting functions in the dependency array can cause problems — either infinite loops or the need for useCallback. But there's a much simpler solution: if a function is only used by one effect, just move it inside that effect.

Why This Works

When you define a function inside your useEffect, it's recreated on every render anyway — but it doesn't matter, because the effect itself decides when to run based on its dependencies. The function isn't in the dependency array anymore, so it can't trigger re-runs.

function Profile({ userId }) {
  // ❌ Function outside creates dependency problems
  // const fetchUser = () => { ... };

  useEffect(() => {
    // ✅ Function inside — no dependency issues
    const fetchUser = async () => {
      const res = await fetch(`/api/users/${userId}`);
      const data = await res.json();
      setUser(data);
    };

    fetchUser();
  }, [userId]); // Only userId matters now
}

When to Use This Pattern

  • The function is only called from one effect
  • The function uses props, state, or other reactive values
  • You want to avoid useCallback complexity

If multiple effects need the same function, then consider useCallback or moving it outside the component entirely.

Key Takeaway: If a helper function is only used inside one useEffect, define it there to avoid dependency headaches and keep your code simple.