Course contentsShow
← React
Lesson 388 of 2,39611. useState Patterns and PitfallsFree lesson

The Performance Problem with Direct Values

Understand how expensive computations in useState arguments run on every render, even though initial state is only used once.

The Performance Problem with Direct Values

You'll learn: why passing expensive computations directly to useState can slow down every render — even though React only uses that initial value once.


When you call useState(initialValue), React only uses that initial value on the very first render. Every subsequent re-render ignores it completely.

But here's the catch: JavaScript still evaluates whatever expression you pass, on every single render.

The Problem in Action

function ProductList() {
  // This runs EVERY render, even though it's only used once!
  const [products, setProducts] = useState(
    JSON.parse(localStorage.getItem('products')) || []
  );

  // More component logic...
}

Every time ProductList re-renders (maybe a button was clicked, or a prop changed), JavaScript executes JSON.parse(localStorage.getItem('products')) again. That's wasted work! React throws the result away because state already exists.

Why This Hurts Performance

Imagine localStorage contains 10,000 products. Parsing that JSON might take 50ms. If your component re-renders 20 times during user interaction, you've wasted 1 full second computing a value React never uses.

The Analogy

It's like asking a chef to prepare an elaborate appetizer every time you walk into the restaurant — even though you only eat it on your first visit. The chef still does the work, wasting time and ingredients, even when the dish goes straight to the trash.


Key Takeaway: Passing expensive computations directly to useState causes performance problems because JavaScript evaluates them on every render, even though React only needs the result once during initialization.