Skip to content

Commit 0891fe4

Browse files
liovicsatnaing
andauthored
perf: fix double-render cycle in useIsMobile hook (#274)
* perf: fix double-render cycle in useIsMobile hook * refactor: extract mobile query into a constant --------- Co-authored-by: satnaing <[email protected]>
1 parent d86ee05 commit 0891fe4

File tree

1 file changed

+10
-13
lines changed

1 file changed

+10
-13
lines changed

src/hooks/use-mobile.tsx

Lines changed: 10 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,16 @@
11
import * as React from 'react'
22

33
const MOBILE_BREAKPOINT = 768
4+
const MOBILE_QUERY = `(max-width: ${MOBILE_BREAKPOINT - 1}px)`
45

56
export function useIsMobile() {
6-
const [isMobile, setIsMobile] = React.useState<boolean | undefined>(undefined)
7-
8-
React.useEffect(() => {
9-
const mql = window.matchMedia(`(max-width: ${MOBILE_BREAKPOINT - 1}px)`)
10-
const onChange = () => {
11-
setIsMobile(window.innerWidth < MOBILE_BREAKPOINT)
12-
}
13-
mql.addEventListener('change', onChange)
14-
setIsMobile(window.innerWidth < MOBILE_BREAKPOINT)
15-
return () => mql.removeEventListener('change', onChange)
16-
}, [])
17-
18-
return !!isMobile
7+
return React.useSyncExternalStore(
8+
(callback) => {
9+
const mql = window.matchMedia(MOBILE_QUERY)
10+
mql.addEventListener('change', callback)
11+
return () => mql.removeEventListener('change', callback)
12+
},
13+
() => window.matchMedia(MOBILE_QUERY).matches,
14+
() => false
15+
)
1916
}

0 commit comments

Comments
 (0)