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

Avoiding the useEffect Computation Trap

Effects for computation cause double-render: render with stale value, effect updates state, re-render. Compute during render instead.

Avoiding the useEffect Computation Trap

What you'll learn: How using effects for computation causes unnecessary double-renders and why computing during render is better.

The Double-Render Problem

When you calculate a value in a useEffect and store it in state, React renders your component twice for every actual change:

  1. First render: Component displays with stale/old computed value
  2. Effect runs: Calculates new value, calls setState
  3. Second render: Component displays with updated value

This is the computation trap—using effects for calculations that could happen during render.

The Wrong Pattern

function ProductList({ products, filter }) {
  const [filtered, setFiltered] = useState([]);

  useEffect(() => {
    // This runs AFTER render
    setFiltered(products.filter(p => p.category === filter));
  }, [products, filter]);

  return <div>{filtered.length} products</div>;
  // First shows old count, then correct count
}

Every time products or filter changes, your component renders with outdated filtered data, then the effect fires and triggers a second render.

The Right Pattern

function ProductList({ products, filter }) {
  // Compute during render
  const filtered = products.filter(p => p.category === filter);

  return <div>{filtered.length} products</div>;
  // Always shows correct count immediately
}

Now you get one render with the correct value. No effect needed. React's render phase is designed for this—computing values based on props and state.

Think of it like this: Don't ask React to "remember to calculate this after displaying," just calculate it before displaying.

Key Takeaway: Compute derived values during render, not in effects. Effects cause double-renders because they update state after the component has already rendered with stale data.