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

Refactoring Effect-Based Derived State

Step-by-step process for removing useEffect when it's only being used to derive values from other state.

Refactoring Effect-Based Derived State

What you'll learn: How to systematically remove unnecessary useEffect calls that only compute values from existing state.

You've learned that deriving state in useEffect creates double-renders and stale data problems. Now let's walk through the actual refactoring process to fix it.

The Step-by-Step Process

Step 1: Identify the Pattern

Look for effects that only calculate a new value and call setState:

// ❌ Before
const [items, setItems] = useState([]);
const [total, setTotal] = useState(0);

useEffect(() => {
  setTotal(items.reduce((sum, item) => sum + item.price, 0));
}, [items]);

If the effect doesn't interact with external systems (network, DOM, timers), it's likely derived state.

Step 2: Remove the Effect and State

Delete the useEffect block entirely. Remove the state variable that held the derived value.

Step 3: Calculate During Render

Move the calculation directly into the component body:

// ✅ After
const [items, setItems] = useState([]);
const total = items.reduce((sum, item) => sum + item.price, 0);

Step 4: Test for Performance

If the calculation is expensive (array processing of thousands of items, complex loops), wrap it in useMemo:

const total = useMemo(
  () => items.reduce((sum, item) => sum + item.price, 0),
  [items]
);

Why This Works

Think of your component like a spreadsheet. When one cell changes, the dependent cells recalculate immediately—they don't wait for a second pass. React renders are the same: compute everything you need in one pass.

Key Takeaway: To refactor effect-based derived state, delete the useEffect and secondary useState, then calculate the value directly during render—wrapping with useMemo only if performance testing proves it necessary.