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

Example: Filtering Props in an Effect

The classic mistake of receiving an array prop, filtering it in useEffect, and storing the result in state.

Example: Filtering Props in an Effect

What you'll learn: The classic beginner mistake of receiving an array prop, filtering it inside useEffect, and storing the filtered result in state instead of computing it directly during render.


The Antipattern

When you receive an array as a prop and need to filter or transform it, it's tempting to do this work inside useEffect and store the result in state:

function ProductList({ products }) {
  const [activeProducts, setActiveProducts] = useState([]);

  useEffect(() => {
    const filtered = products.filter(p => p.isActive);
    setActiveProducts(filtered);
  }, [products]);

  return <div>{activeProducts.map(...)}</div>;
}

This feels logical: "whenever products changes, re-filter and update state." But it introduces unnecessary complexity and timing issues.

Why It's Wrong

You've created derived state—state that's computed from props or other state. Problems:

  1. Render delay: On first render, activeProducts is [], then the effect runs and triggers a second render with the filtered list
  2. Extra state: You're storing data that could be calculated on-the-fly
  3. Synchronization burden: The effect must re-run every time products changes

The Right Approach

Just compute it during render:

function ProductList({ products }) {
  const activeProducts = products.filter(p => p.isActive);

  return <div>{activeProducts.map(...)}</div>;
}

No effect. No extra state. No delays. The filtering happens every render, which is perfectly fine—filtering arrays is fast, and React's rendering is optimized for this.

Key Takeaway: Don't use useEffect to transform props into state. Compute derived values directly during render—it's simpler, faster, and eliminates synchronization bugs.