The Fix: Compute During Render
You'll learn: How to avoid unnecessary useEffect calls by calculating derived values directly during render instead.
When you need a value that's based on props or state, your first instinct might be to use useEffect to update a separate state variable whenever the source changes. But there's a simpler, more React-friendly way: just calculate it during render.
The Core Idea
If you can compute a value from existing props or state, do it right in your component body. Don't store it in state. Don't put it in an effect. Just calculate it.
function ProductList({ products, searchTerm }) {
// ✅ GOOD: Compute during render
const filteredProducts = products.filter(p =>
p.name.toLowerCase().includes(searchTerm.toLowerCase())
);
return <ul>{filteredProducts.map(/* ... */)}</ul>;
}
Compare that to the problematic effect version from the previous lesson:
// ❌ BAD: Using effect for derived data
const [filteredProducts, setFilteredProducts] = useState([]);
useEffect(() => {
setFilteredProducts(
products.filter(p => p.name.toLowerCase().includes(searchTerm.toLowerCase()))
);
}, [products, searchTerm]);
Why It's Better
When you compute during render:
- Always in sync: No delay, no stale values
- One render: No extra render triggered by
setState - Simpler code: Fewer lines, no dependency management
- Easier to debug: The value is right there where you can see it
Think of it like baking: you don't bake a cake, freeze it, then reheat it when someone asks for cake. You just bake it when needed.
Performance Consideration
"But won't this slow down every render?" Only if the calculation is genuinely expensive. For 99% of cases (filtering arrays, concatenating strings, simple math), it's negligible. If it is slow, then reach for useMemo — not useEffect.
Key Takeaway: If a value can be calculated from props or state, calculate it during render. Save useEffect for actual side effects like fetching data or subscribing to external systems.