Loading source
Pulling the file list, source metadata, and syntax-aware rendering for this listing.
Source from repo
Apply 62 React and Next.js performance optimization rules from Vercel Engineering
Files
Skill
Size
Entrypoint
Format
Open file
Syntax-highlighted preview of this file as included in the skill package.
rules/rerender-lazy-state-init.md
1---2title: Use Lazy State Initialization3impact: MEDIUM4impactDescription: wasted computation on every render5tags: react, hooks, useState, performance, initialization6---78## Use Lazy State Initialization910Pass a function to `useState` for expensive initial values. Without the function form, the initializer runs on every render even though the value is only used once.1112**Incorrect (runs on every render):**1314```tsx15function FilteredList({ items }: { items: Item[] }) {16// buildSearchIndex() runs on EVERY render, even after initialization17const [searchIndex, setSearchIndex] = useState(buildSearchIndex(items))18const [query, setQuery] = useState('')1920// When query changes, buildSearchIndex runs again unnecessarily21return <SearchResults index={searchIndex} query={query} />22}2324function UserProfile() {25// JSON.parse runs on every render26const [settings, setSettings] = useState(27JSON.parse(localStorage.getItem('settings') || '{}')28)2930return <SettingsForm settings={settings} onChange={setSettings} />31}32```3334**Correct (runs only once):**3536```tsx37function FilteredList({ items }: { items: Item[] }) {38// buildSearchIndex() runs ONLY on initial render39const [searchIndex, setSearchIndex] = useState(() => buildSearchIndex(items))40const [query, setQuery] = useState('')4142return <SearchResults index={searchIndex} query={query} />43}4445function UserProfile() {46// JSON.parse runs only on initial render47const [settings, setSettings] = useState(() => {48const stored = localStorage.getItem('settings')49return stored ? JSON.parse(stored) : {}50})5152return <SettingsForm settings={settings} onChange={setSettings} />53}54```5556Use lazy initialization when computing initial values from localStorage/sessionStorage, building data structures (indexes, maps), reading from the DOM, or performing heavy transformations.5758For simple primitives (`useState(0)`), direct references (`useState(props.value)`), or cheap literals (`useState({})`), the function form is unnecessary.59