Course contentsShow
← React
Lesson 356 of 2,39610. useState BasicsFree lesson

When Initial State is Expensive to Compute

Avoid running expensive calculations on every render when setting initial state.

When Initial State is Expensive to Compute

What you'll learn: How to avoid running expensive calculations on every render when setting initial state.

The Problem

When you call useState(someValue), React uses that value as the initial state — but here's the catch: React evaluates whatever you pass to useState() on every render, even though it only uses the initial value on the very first render.

If that value comes from an expensive calculation, you're wasting performance on every re-render:

// ❌ Bad: expensiveCalculation() runs on EVERY render
const [data, setData] = useState(expensiveCalculation());

Even though React ignores the result after the first render, JavaScript still executes expensiveCalculation() every single time your component renders.

The Solution: Lazy Initialization

Pass a function to useState instead of a value. React will only call that function once, during the initial render:

// ✅ Good: expensiveCalculation() runs ONLY on mount
const [data, setData] = useState(() => expensiveCalculation());

Notice the arrow function () => wrapper. You're not calling the expensive function directly — you're giving React a function it can call when it needs to.

When Does This Matter?

  • Reading from localStorage
  • Parsing large JSON
  • Complex computations based on props
  • Generating unique IDs

If your initial state is just a simple value (0, "", false), don't bother with a function — the overhead isn't worth it.

The Analogy

Think of it like a recipe card vs. cooking a meal. Passing a value is like cooking the entire meal every time someone walks into the kitchen. Passing a function is like handing React a recipe card that says "only cook this if we need it for the first time."

Key Takeaway: When initial state is expensive to compute, pass a function to useState(() => expensiveCalculation()) so it only runs once, not on every render.