fb79a15508
- 添加 sections 定义文件,包含性能优化各领域分类 - 添加规则模板文件,规范文档结构和标签定义 - 添加异步操作优化规则,包括防止瀑布流、并行化、延迟等待等 - 添加包大小优化规则,包括避免桶式导入、动态导入、预加载等 - 添加服务端性能优化规则,包括 API 路
43 lines
958 B
Markdown
43 lines
958 B
Markdown
---
|
|
title: Initialize App Once, Not Per Mount
|
|
impact: LOW-MEDIUM
|
|
impactDescription: avoids duplicate init in development
|
|
tags: initialization, useEffect, app-startup, side-effects
|
|
---
|
|
|
|
## Initialize App Once, Not Per Mount
|
|
|
|
Do not put app-wide initialization that must run once per app load inside `useEffect([])` of a component. Components can remount and effects will re-run. Use a module-level guard or top-level init in the entry module instead.
|
|
|
|
**Incorrect (runs twice in dev, re-runs on remount):**
|
|
|
|
```tsx
|
|
function Comp() {
|
|
useEffect(() => {
|
|
loadFromStorage()
|
|
checkAuthToken()
|
|
}, [])
|
|
|
|
// ...
|
|
}
|
|
```
|
|
|
|
**Correct (once per app load):**
|
|
|
|
```tsx
|
|
let didInit = false
|
|
|
|
function Comp() {
|
|
useEffect(() => {
|
|
if (didInit) return
|
|
didInit = true
|
|
loadFromStorage()
|
|
checkAuthToken()
|
|
}, [])
|
|
|
|
// ...
|
|
}
|
|
```
|
|
|
|
Reference: [Initializing the application](https://react.dev/learn/you-might-not-need-an-effect#initializing-the-application)
|