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

Lazy Initial State with a Function

Pass a function to useState to compute initial state only once on mount.

What You'll Learn

You'll learn how to pass a function to useState so React computes your initial state value only once, avoiding unnecessary recalculations on every render.


The Problem with Expensive Initial State

Sometimes your initial state requires an expensive operation—like parsing large JSON, reading from localStorage, or performing calculations. If you pass that value directly to useState, React runs that expensive code on every render, even though it only uses the result once:

// ❌ Runs expensive calculation on EVERY render
const [data, setData] = useState(JSON.parse(localStorage.getItem('bigData')));

This is wasteful. React only uses the initial state on the very first render (mount), but the code above recalculates it every single time the component re-renders.


The Solution: Lazy Initialization

Pass a function to useState instead. React will call that function only once during the initial mount:

// ✅ Runs expensive calculation ONLY on mount
const [data, setData] = useState(() => {
  return JSON.parse(localStorage.getItem('bigData'));
});

Notice the function syntax: () => .... React sees this and knows to execute it only the first time. On subsequent re-renders, React skips calling the function entirely.


When to Use It

Use lazy initialization when:

  • Your initial state involves heavy computation
  • You're reading from localStorage or sessionStorage
  • You're processing large data structures

For simple values like useState(0) or useState(''), direct values are fine—no performance benefit from wrapping them.


Key Takeaway: Pass a function to useState when computing initial state is expensive—React will call it only once on mount, not on every re-render.