1000 B
1000 B
title, impact, impactDescription, tags
| title | impact | impactDescription | tags |
|---|---|---|---|
| Defer State Reads to Usage Point | MEDIUM | 避免不必要的订阅 | rerender, searchParams, localStorage, optimization |
将状态读取推迟到使用点
不要在回调函数之外订阅动态状态(searchParams、localStorage),如果只在回调内部读取它的话。
错误做法(订阅了所有 searchParams 变化):
function ShareButton({ chatId }: { chatId: string }) {
const searchParams = useSearchParams()
const handleShare = () => {
const ref = searchParams.get('ref')
shareChat(chatId, { ref })
}
return <button onClick={handleShare}>Share</button>
}
正确做法(按需读取,无需订阅):
function ShareButton({ chatId }: { chatId: string }) {
const handleShare = () => {
const params = new URLSearchParams(window.location.search)
const ref = params.get('ref')
shareChat(chatId, { ref })
}
return <button onClick={handleShare}>Share</button>
}