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

Arrays from .map and .filter

Learn why [items.map(i => i.id)] creates a new array every render and how to handle dynamic array dependencies correctly.

Arrays from .map and .filter

You'll learn why creating arrays with .map() or .filter() inside your component body causes your effects to re-run unexpectedly.

The Invisible New Array Problem

Every time you write items.map(i => i.id) or items.filter(i => i.active), JavaScript creates a brand new array, even if the data inside is identical. When you pass this array into a useEffect dependency array, React sees a different reference every render and re-runs your effect:

function ProductList({ items }) {
  useEffect(() => {
    // Runs on EVERY render, even if items hasn't changed
  }, [items.map(i => i.id)]);  // ❌ New array every time
}

Think of it like making a fresh photocopy each time: the content looks the same, but it's a different piece of paper. React compares by reference, not by content.

The Solution: Memoize or Use the Original

If you need a derived array as a dependency, wrap it in useMemo:

const itemIds = useMemo(() => items.map(i => i.id), [items]);

useEffect(() => {
  // Now only runs when items actually changes
}, [itemIds]);

Or better yet, depend on the original array if possible:

useEffect(() => {
  const ids = items.map(i => i.id);
  // Use ids here
}, [items]);  // ✅ Depend on the source

Move the transformation inside the effect body when you can.

Key Takeaway: Never put .map() or .filter() directly in a dependency array—they create new arrays every render. Use useMemo to stabilize the reference, or move the transformation inside the effect.