Function Form: useState(() => value)
You'll learn the exact syntax for lazy initialization—wrapping your initial value in a function—so expensive operations run only once when the component mounts.
The Problem Recap
In the previous lesson, you learned why lazy initialization exists: if you pass an expensive value directly to useState, React re-executes that expensive operation on every render, even though it only uses the result once (on mount). That's wasteful.
The Solution: Arrow Function Wrapper
The function form of useState solves this. Instead of passing the value directly, you pass a function that returns the value:
const [state, setState] = useState(() => expensiveComputation());
Notice the arrow function: () => expensiveComputation(). This is called an initializer function.
How It Works
React calls your initializer function only on the first render. On subsequent re-renders, React sees you provided a function, recognizes it as lazy initialization, and skips calling it entirely. The expensive work happens once, not on every render.
The Syntax Pattern
// ❌ Expensive value runs every render
const [data, setData] = useState(readFromLocalStorage());
// ✅ Function runs only once
const [data, setData] = useState(() => readFromLocalStorage());
The function takes no arguments and returns the initial state value. You can also write it with a function body:
const [user, setUser] = useState(() => {
const stored = localStorage.getItem('user');
return stored ? JSON.parse(stored) : null;
});
When to Use It
Use the function form whenever your initial state requires computation: reading from localStorage, processing arrays, filtering data, or any operation that takes time.
Key Takeaway: Wrap expensive initial state in an arrow function () => value to guarantee React computes it only once, on mount, not on every render.