fb79a15508
- 添加 sections 定义文件,包含性能优化各领域分类 - 添加规则模板文件,规范文档结构和标签定义 - 添加异步操作优化规则,包括防止瀑布流、并行化、延迟等待等 - 添加包大小优化规则,包括避免桶式导入、动态导入、预加载等 - 添加服务端性能优化规则,包括 API 路
41 lines
1.0 KiB
Markdown
41 lines
1.0 KiB
Markdown
---
|
|
title: Use Transitions for Non-Urgent Updates
|
|
impact: MEDIUM
|
|
impactDescription: maintains UI responsiveness
|
|
tags: rerender, transitions, startTransition, performance
|
|
---
|
|
|
|
## Use Transitions for Non-Urgent Updates
|
|
|
|
Mark frequent, non-urgent state updates as transitions to maintain UI responsiveness.
|
|
|
|
**Incorrect (blocks UI on every scroll):**
|
|
|
|
```tsx
|
|
function ScrollTracker() {
|
|
const [scrollY, setScrollY] = useState(0)
|
|
useEffect(() => {
|
|
const handler = () => setScrollY(window.scrollY)
|
|
window.addEventListener('scroll', handler, { passive: true })
|
|
return () => window.removeEventListener('scroll', handler)
|
|
}, [])
|
|
}
|
|
```
|
|
|
|
**Correct (non-blocking updates):**
|
|
|
|
```tsx
|
|
import { startTransition } from 'react'
|
|
|
|
function ScrollTracker() {
|
|
const [scrollY, setScrollY] = useState(0)
|
|
useEffect(() => {
|
|
const handler = () => {
|
|
startTransition(() => setScrollY(window.scrollY))
|
|
}
|
|
window.addEventListener('scroll', handler, { passive: true })
|
|
return () => window.removeEventListener('scroll', handler)
|
|
}, [])
|
|
}
|
|
```
|