File tree Expand file tree Collapse file tree 1 file changed +27
-13
lines changed
Expand file tree Collapse file tree 1 file changed +27
-13
lines changed Original file line number Diff line number Diff line change 1- import { useEffect , useState } from 'react' ;
1+ import { useSyncExternalStore } from 'react' ;
22
33const MOBILE_BREAKPOINT = 768 ;
44
5- export function useIsMobile ( ) {
6- const [ isMobile , setIsMobile ] = useState < boolean > ( ) ;
5+ const mql =
6+ typeof window === 'undefined'
7+ ? undefined
8+ : window . matchMedia ( `(max-width: ${ MOBILE_BREAKPOINT - 1 } px)` ) ;
79
8- useEffect ( ( ) => {
9- const mql = window . matchMedia ( `(max-width: ${ MOBILE_BREAKPOINT - 1 } px)` ) ;
10+ function mediaQueryListener ( callback : ( event : MediaQueryListEvent ) => void ) {
11+ if ( ! mql ) {
12+ return ( ) => { } ;
13+ }
1014
11- const onChange = ( ) => {
12- setIsMobile ( window . innerWidth < MOBILE_BREAKPOINT ) ;
13- } ;
15+ mql . addEventListener ( 'change' , callback ) ;
1416
15- mql . addEventListener ( 'change' , onChange ) ;
16- setIsMobile ( window . innerWidth < MOBILE_BREAKPOINT ) ;
17+ return ( ) => {
18+ mql . removeEventListener ( 'change' , callback ) ;
19+ } ;
20+ }
21+
22+ function isSmallerThanBreakpoint ( ) : boolean {
23+ return mql ?. matches ?? false ;
24+ }
1725
18- return ( ) => mql . removeEventListener ( 'change' , onChange ) ;
19- } , [ ] ) ;
26+ function getServerSnapshot ( ) : boolean {
27+ return false ;
28+ }
2029
21- return ! ! isMobile ;
30+ export function useIsMobile ( ) : boolean {
31+ return useSyncExternalStore (
32+ mediaQueryListener ,
33+ isSmallerThanBreakpoint ,
34+ getServerSnapshot
35+ ) ;
2236}
You can’t perform that action at this time.
0 commit comments