Skip to content

Commit d8acc1f

Browse files
committed
update use-mobile
1 parent 3c5620f commit d8acc1f

File tree

1 file changed

+27
-13
lines changed

1 file changed

+27
-13
lines changed

resources/js/hooks/use-mobile.tsx

Lines changed: 27 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,36 @@
1-
import { useEffect, useState } from 'react';
1+
import { useSyncExternalStore } from 'react';
22

33
const 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
}

0 commit comments

Comments
 (0)