What is Lazy Initialization?
You'll learn why passing a function to useState prevents React from running expensive calculations on every render—only computing the initial state once when the component first mounts.
The Problem with Direct Initial State
When you write useState(expensiveCalculation()), React calls that function on every single render—even though it only uses the result during the very first render. This is wasteful:
// ❌ Runs the calculation on EVERY render
const [data, setData] = useState(processLargeDataset());
React evaluates processLargeDataset() immediately every time your component re-renders, then throws away the result after the first render. It's like baking a cake every morning even though you only eat it once.
The Solution: Lazy Initialization
Pass a function to useState instead of calling it directly. React will only execute that function once, during the initial mount:
// ✅ Only runs the calculation ONCE, on mount
const [data, setData] = useState(() => processLargeDataset());
Notice the arrow function wrapper: () => processLargeDataset(). This defers the expensive work until React actually needs it—and React is smart enough to never call it again.
When to Use It
Lazy initialization matters when your initial state requires:
- Complex calculations
- Reading from
localStorage - Processing large data structures
- Any operation that takes noticeable time
For simple values like useState(0) or useState(false), don't bother—the overhead is negligible.
The Key Difference
Direct call: React runs it every render, wastes cycles.
Function wrapper: React runs it once, saves performance.
Key Takeaway: Wrapping expensive initial state in a function (useState(() => ...)) ensures React only computes it once when the component mounts, not on every re-render—this is called lazy initialization.