返回 AiToEarn
rerender-derived-state.md
1 ---
2 title: Subscribe to Derived State
3 impact: MEDIUM
4 impactDescription: reduces re-render frequency
5 tags: rerender, derived-state, media-query, optimization
6 ---
7
8 ## Subscribe to Derived State
9
10 Subscribe to derived boolean state instead of continuous values to reduce re-render frequency.
11
12 **Incorrect (re-renders on every pixel change):**
13
14 ```tsx
15 function Sidebar() {
16 const width = useWindowWidth() // updates continuously
17 const isMobile = width < 768
18 return <nav className={isMobile ? 'mobile' : 'desktop'} />
19 }
20 ```
21
22 **Correct (re-renders only when boolean changes):**
23
24 ```tsx
25 function Sidebar() {
26 const isMobile = useMediaQuery('(max-width: 767px)')
27 return <nav className={isMobile ? 'mobile' : 'desktop'} />
28 }
29 ```
30
30 lines MARKDOWN