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