Course contentsShow
← React
Lesson 771 of 2,39620. useReducerFree lesson

The Problem: Expensive Initial State Computation

Understanding why calculating complex initial state inline can hurt performance on every render, even when it's only needed once.

The Problem: Expensive Initial State Computation

What you'll learn: Why calculating complex initial state values directly in your component body can waste performance on every single render.

The Hidden Cost of Inline Calculations

When you use useReducer (or useState), you might be tempted to calculate the initial state value right where you declare it:

const initialState = expensiveCalculation(); // Runs EVERY render!

const [state, dispatch] = useReducer(reducer, initialState);

Here's the problem: even though React only uses that initial value on the first render, JavaScript evaluates that expression on every render. If expensiveCalculation() involves filtering large arrays, parsing JSON, reading localStorage, or complex transformations, you're paying that performance cost repeatedly for no benefit.

The Analogy

Imagine a restaurant that calculates the entire menu's nutritional information fresh every time a waiter walks past the kitchen—even though the menu only needs to be printed once at opening time. That's what happens when you compute expensive initial state inline.

What Makes Computation "Expensive"?

  • Reading from localStorage and parsing JSON
  • Filtering/mapping large datasets
  • Complex mathematical operations
  • Generating IDs or UUIDs
  • Any synchronous operation that takes noticeable time

On subsequent renders, React ignores the initial state parameter entirely, but your expensive function still runs because JavaScript evaluates arguments before passing them to functions.

Key Takeaway: Calculating expensive initial state inline wastes performance on every render because JavaScript executes it even when React doesn't need it—you need a way to defer the calculation until it's actually required.