Agent Skills: rerender-lazy-state

Use lazy state initialization with useState function form. Apply when computing expensive initial values like building search indexes, parsing JSON, or complex calculations.

UncategorizedID: theorcdev/8bitcn-ui/rerender-lazy-state

Install this agent skill to your local

pnpm dlx add-skill https://github.com/TheOrcDev/8bitcn-ui/tree/HEAD/.claude/skills/rerender-lazy-state

Skill Files

Browse the full folder contents for rerender-lazy-state.

Download Skill

Loading file tree…

.claude/skills/rerender-lazy-state/SKILL.md

Skill Metadata

Name
rerender-lazy-state
Description
Use lazy state initialization with useState function form. Apply when computing expensive initial values like building search indexes, parsing JSON, or complex calculations.

Use Lazy State Initialization

Pass 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.

Incorrect (runs on every render):

function FilteredList({ items }: { items: Item[] }) {
  // buildSearchIndex() runs on EVERY render, even after initialization
  const [searchIndex, setSearchIndex] = useState(buildSearchIndex(items))
  const [query, setQuery] = useState('')

  // When query changes, buildSearchIndex runs again unnecessarily
  return <SearchResults index={searchIndex} query={query} />
}

function UserProfile() {
  // JSON.parse runs on every render
  const [settings, setSettings] = useState(
    JSON.parse(localStorage.getItem('settings') || '{}')
  )

  return <SettingsForm settings={settings} onChange={setSettings} />
}

Correct (runs only once):

function FilteredList({ items }: { items: Item[] }) {
  // buildSearchIndex() runs ONLY on initial render
  const [searchIndex, setSearchIndex] = useState(() => buildSearchIndex(items))
  const [query, setQuery] = useState('')

  return <SearchResults index={searchIndex} query={query} />
}

function UserProfile() {
  // JSON.parse runs only on initial render
  const [settings, setSettings] = useState(() => {
    const stored = localStorage.getItem('settings')
    return stored ? JSON.parse(stored) : {}
  })

  return <SettingsForm settings={settings} onChange={setSettings} />
}

Use lazy initialization when computing initial values from localStorage/sessionStorage, building data structures (indexes, maps), reading from the DOM, or performing heavy transformations.

For simple primitives (useState(0)), direct references (useState(props.value)), or cheap literals (useState({})), the function form is unnecessary.

rerender-lazy-state Skill | Agent Skills