2026-03-09 22:47:14 -07:00
|
|
|
---
|
|
|
|
|
title: Defer State Reads to Usage Point
|
|
|
|
|
impact: MEDIUM
|
|
|
|
|
impactDescription: avoids unnecessary subscriptions
|
|
|
|
|
tags: rerender, searchParams, localStorage, optimization
|
|
|
|
|
---
|
|
|
|
|
|
|
|
|
|
## Defer State Reads to Usage Point
|
|
|
|
|
|
|
|
|
|
Don't subscribe to dynamic state (searchParams, localStorage) if you only read it inside callbacks.
|
|
|
|
|
|
|
|
|
|
**Incorrect (subscribes to all searchParams changes):**
|
|
|
|
|
|
|
|
|
|
```tsx
|
2026-05-14 14:46:48 +05:30
|
|
|
import { Button } from '@/components/ui/button'
|
|
|
|
|
|
2026-03-09 22:47:14 -07:00
|
|
|
function ShareButton({ chatId }: { chatId: string }) {
|
|
|
|
|
const searchParams = useSearchParams()
|
|
|
|
|
|
|
|
|
|
const handleShare = () => {
|
|
|
|
|
const ref = searchParams.get('ref')
|
|
|
|
|
shareChat(chatId, { ref })
|
|
|
|
|
}
|
|
|
|
|
|
2026-05-14 14:46:48 +05:30
|
|
|
return <Button onClick={handleShare}>Share</Button>
|
2026-03-09 22:47:14 -07:00
|
|
|
}
|
|
|
|
|
```
|
|
|
|
|
|
|
|
|
|
**Correct (reads on demand, no subscription):**
|
|
|
|
|
|
|
|
|
|
```tsx
|
2026-05-14 14:46:48 +05:30
|
|
|
import { Button } from '@/components/ui/button'
|
|
|
|
|
|
2026-03-09 22:47:14 -07:00
|
|
|
function ShareButton({ chatId }: { chatId: string }) {
|
|
|
|
|
const handleShare = () => {
|
|
|
|
|
const params = new URLSearchParams(window.location.search)
|
|
|
|
|
const ref = params.get('ref')
|
|
|
|
|
shareChat(chatId, { ref })
|
|
|
|
|
}
|
|
|
|
|
|
2026-05-14 14:46:48 +05:30
|
|
|
return <Button onClick={handleShare}>Share</Button>
|
2026-03-09 22:47:14 -07:00
|
|
|
}
|
|
|
|
|
```
|