React Core & Hooks (407 Qs)•Part 9: React Hooks Deep Dive (262 - 316)
Can useState take a function as an initial value?
mid LevelCode ExampleHooks
Yes, useState accepts an initialization function (called Lazy Initial State).
Why Use Lazy Initialization?
When the initial state requires an expensive computation (e.g., parsing a large localStorage item, filtering an array, or computing cryptographic hashes), passing a value directly runs on every re-render:
useState(expensiveCalculation()):expensiveCalculation()executes on every single render, but React discards the result after mount!useState(() => expensiveCalculation()): The function is executed only once on initial mount, saving valuable CPU cycles.
Code Example
jsx
import { useState } from 'react';
export function UserPreferences() {
// ✅ Lazy state initialization: runs ONLY on mount
const [theme, setTheme] = useState(() => {
try {
const saved = window.localStorage.getItem('app_theme');
return saved ? JSON.parse(saved) : 'system';
} catch {
return 'system';
}
});
return <button onClick={() => setTheme('dark')}>Current Theme: {theme}</button>;
}