Computing Derived Initial State
What you'll learn: How to use lazy initialization when your initial state needs calculations based on props or other available data at mount time.
Sometimes your component's initial state isn't a simple value—it's derived from props, configuration, or other data. You might need to perform calculations, transformations, or lookups to determine what the starting state should be.
The Problem
Imagine you receive a userId prop and need to initialize state with a processed version:
// ❌ This calculation runs on EVERY render
const [displayName, setDisplayName] = useState(
formatUserName(props.userId, userData)
);
Even though initial state only matters once, this expensive formatUserName function runs every single time your component re-renders.
The Solution: Lazy Initialization with Derived Logic
Pass a function to useState that performs the calculation:
// ✅ Calculation runs ONLY on mount
const [displayName, setDisplayName] = useState(() =>
formatUserName(props.userId, userData)
);
The function receives no arguments but has access to props and any other data in scope at mount time.
Real-World Example
function UserProfile({ userId, config }) {
const [settings, setSettings] = useState(() => {
// Compute initial settings based on props
const defaults = config.defaults;
const userPrefs = lookupPreferences(userId);
return { ...defaults, ...userPrefs };
});
// settings only computed once when component mounts
}
This pattern combines two concepts you've learned: lazy initialization (for performance) and deriving values from props (for dynamic initial state).
Key Takeaway: Use lazy initialization with a function when your initial state requires calculations based on props or other mount-time data—this ensures expensive operations run only once, not on every render.