Course contentsShow
← React
Lesson 694 of 2,39618. When NOT to Use useEffectFree lesson

The Effect Antipattern: Computing Derived Values

Using useEffect to compute values from state/props creates stale-value windows and extra renders. Compute directly in render body.

The Effect Antipattern: Computing Derived Values

What you'll learn: Why using useEffect to compute values from existing state or props is an antipattern that causes unnecessary re-renders and stale data windows.

The Core Problem

When you have data that can be calculated from state or props, a common mistake is reaching for useEffect to do the computation:

// ❌ ANTIPATTERN: Computing in an Effect
function ProductList({ products }) {
  const [filteredProducts, setFilteredProducts] = useState([]);

  useEffect(() => {
    setFilteredProducts(products.filter(p => p.inStock));
  }, [products]);

  return <div>{/* render filteredProducts */}</div>;
}

This creates two major problems:

  1. Double rendering: First render shows stale/empty data, second render shows the computed value
  2. Stale value window: Between when products changes and the Effect runs, your UI displays outdated information

The Solution: Compute During Render

Just calculate the value directly in your component body:

// ✅ CORRECT: Compute during render
function ProductList({ products }) {
  const filteredProducts = products.filter(p => p.inStock);

  return <div>{/* render filteredProducts */}</div>;
}

Now there's only one render with the correct data. No stale windows. No extra cycles.

The Mental Model

Think of Effects as tools for synchronizing with external systems (timers, network, subscriptions), not for transforming data you already have. If you can compute something from current props/state, do it immediately — don't defer it to an Effect.

Key Takeaway: Derived values should be computed directly during render, not in useEffect. Effects are for synchronization with external systems, not for data transformation.