ReactuseState懒初始化Skill rerender-lazy-state

此技能涉及在React前端开发中使用useState函数的懒初始化技术,以避免在每次渲染时重复计算昂贵的初始值,提高应用性能。适用于构建搜索索引、解析JSON或复杂计算等场景。关键词:React, useState, 懒初始化, 性能优化, 前端开发

前端开发 0 次安装 0 次浏览 更新于 3/9/2026

名称: rerender-lazy-state 描述: 使用useState函数形式的懒状态初始化。适用于计算昂贵的初始值,如构建搜索索引、解析JSON或复杂计算。

使用懒状态初始化

对于昂贵的初始值,向useState传递一个函数。如果没有函数形式,即使值只使用一次,初始化器也会在每次渲染时运行。

错误(每次渲染都运行):

function FilteredList({ items }: { items: Item[] }) {
  // buildSearchIndex() 在每次渲染时运行,即使在初始化后
  const [searchIndex, setSearchIndex] = useState(buildSearchIndex(items))
  const [query, setQuery] = useState('')

  // 当查询改变时,buildSearchIndex不必要地再次运行
  return <SearchResults index={searchIndex} query={query} />
}

function UserProfile() {
  // JSON.parse在每次渲染时运行
  const [settings, setSettings] = useState(
    JSON.parse(localStorage.getItem('settings') || '{}')
  )

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

正确(只运行一次):

function FilteredList({ items }: { items: Item[] }) {
  // buildSearchIndex() 仅在初始渲染时运行
  const [searchIndex, setSearchIndex] = useState(() => buildSearchIndex(items))
  const [query, setQuery] = useState('')

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

function UserProfile() {
  // JSON.parse仅在初始渲染时运行
  const [settings, setSettings] = useState(() => {
    const stored = localStorage.getItem('settings')
    return stored ? JSON.parse(stored) : {}
  })

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

当从localStorage/sessionStorage计算初始值、构建数据结构(索引、映射)、从DOM读取或执行繁重转换时,使用懒初始化。

对于简单原始值(useState(0))、直接引用(useState(props.value))或廉价字面量(useState({})),函数形式是不必要的。