返回 AiToEarn
rerender-defer-reads.md
1 ---
2 title: Defer State Reads to Usage Point
3 impact: MEDIUM
4 impactDescription: avoids unnecessary subscriptions
5 tags: rerender, searchParams, localStorage, optimization
6 ---
7
8 ## Defer State Reads to Usage Point
9
10 Don't subscribe to dynamic state (searchParams, localStorage) if you only read it inside callbacks.
11
12 **Incorrect (subscribes to all searchParams changes):**
13
14 ```tsx
15 function ShareButton({ chatId }: { chatId: string }) {
16 const searchParams = useSearchParams()
17
18 const handleShare = () => {
19 const ref = searchParams.get('ref')
20 shareChat(chatId, { ref })
21 }
22
23 return <button onClick={handleShare}>Share</button>
24 }
25 ```
26
27 **Correct (reads on demand, no subscription):**
28
29 ```tsx
30 function ShareButton({ chatId }: { chatId: string }) {
31 const handleShare = () => {
32 const params = new URLSearchParams(window.location.search)
33 const ref = params.get('ref')
34 shareChat(chatId, { ref })
35 }
36
37 return <button onClick={handleShare}>Share</button>
38 }
39 ```
40
40 lines MARKDOWN