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:
- Render delay: On first render,
activeProductsis[], then the effect runs and triggers a second render with the filtered list - Extra state: You're storing data that could be calculated on-the-fly
- Synchronization burden: The effect must re-run every time
productschanges
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.