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

Destructuring Object Props in Dependencies

Depend on primitive values from objects (user.id) instead of the whole object to avoid unnecessary effect runs.

Destructuring Object Props in Dependencies

What you'll learn: How to depend on specific primitive values from objects instead of the whole object to prevent your effects from re-running unnecessarily.

The Core Problem

When you put an object in your dependency array, React checks if it's the same reference as before. Even if the values inside haven't changed, if it's a new object reference, your effect runs again. This leads to wasted re-runs.

The solution? Extract the specific primitive values you actually need.

Before: Depending on the Whole Object

function UserProfile({ user }) {
  useEffect(() => {
    fetchUserPosts(user.id);
    // Re-runs whenever 'user' object reference changes
    // even if user.id is the same!
  }, [user]);
}

If the parent re-renders and creates a new user object (but with the same id), your effect runs again even though nothing meaningful changed.

After: Destructure First, Depend on Primitives

function UserProfile({ user }) {
  const userId = user.id; // Extract the primitive

  useEffect(() => {
    fetchUserPosts(userId);
    // Only re-runs when userId actually changes
  }, [userId]);
}

Now React compares userId (a number or string) by value, not reference. If user.id is 123 before and after, the effect doesn't re-run.

Why This Works

Primitives like strings, numbers, and booleans are compared by their actual value. Objects are compared by their memory address. By pulling out just the values you need, you tell React exactly what changes should trigger your effect.

Key Takeaway: Always destructure objects and depend on the specific primitive values your effect actually uses, not the whole object. This prevents unnecessary re-runs caused by reference changes when the data you care about hasn't actually changed.