fb79a15508
- 添加 sections 定义文件,包含性能优化各领域分类 - 添加规则模板文件,规范文档结构和标签定义 - 添加异步操作优化规则,包括防止瀑布流、并行化、延迟等待等 - 添加包大小优化规则,包括避免桶式导入、动态导入、预加载等 - 添加服务端性能优化规则,包括 API 路
1.8 KiB
1.8 KiB
title, impact, impactDescription, tags
| title | impact | impactDescription | tags |
|---|---|---|---|
| Do Not Put Effect Events in Dependency Arrays | LOW | avoids unnecessary effect re-runs and lint errors | advanced, hooks, useEffectEvent, dependencies, effects |
Do Not Put Effect Events in Dependency Arrays
Effect Event functions do not have a stable identity. Their identity intentionally changes on every render. Do not include the function returned by useEffectEvent in a useEffect dependency array. Keep the actual reactive values as dependencies and call the Effect Event from inside the effect body or subscriptions created by that effect.
Incorrect (Effect Event added as a dependency):
import { useEffect, useEffectEvent } from 'react'
function ChatRoom({ roomId, onConnected }: {
roomId: string
onConnected: () => void
}) {
const handleConnected = useEffectEvent(onConnected)
useEffect(() => {
const connection = createConnection(roomId)
connection.on('connected', handleConnected)
connection.connect()
return () => connection.disconnect()
}, [roomId, handleConnected])
}
Including the Effect Event in dependencies makes the effect re-run every render and triggers the React Hooks lint rule.
Correct (depend on reactive values, not the Effect Event):
import { useEffect, useEffectEvent } from 'react'
function ChatRoom({ roomId, onConnected }: {
roomId: string
onConnected: () => void
}) {
const handleConnected = useEffectEvent(onConnected)
useEffect(() => {
const connection = createConnection(roomId)
connection.on('connected', handleConnected)
connection.connect()
return () => connection.disconnect()
}, [roomId])
}
Reference: React useEffectEvent: Effect Event in deps