Skip to content

Commit 490314f

Browse files
authored
Fixed an error (ReferenceError: window is not defined) when Server Side Rendering (SSR) is running. (#210)
1 parent 395ac18 commit 490314f

File tree

1 file changed

+20
-5
lines changed

1 file changed

+20
-5
lines changed

resources/js/hooks/use-mobile.tsx

Lines changed: 20 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,20 +2,35 @@ import { useSyncExternalStore } from 'react';
22

33
const MOBILE_BREAKPOINT = 768;
44

5-
const mql = window.matchMedia(`(max-width: ${MOBILE_BREAKPOINT - 1}px)`);
5+
const mql =
6+
typeof window === 'undefined'
7+
? undefined
8+
: window.matchMedia(`(max-width: ${MOBILE_BREAKPOINT - 1}px)`);
69

710
function mediaQueryListener(callback: (event: MediaQueryListEvent) => void) {
11+
if (!mql) {
12+
return () => {};
13+
}
14+
815
mql.addEventListener('change', callback);
916

1017
return () => {
1118
mql.removeEventListener('change', callback);
1219
};
1320
}
1421

15-
function isSmallerThanBreakpoint() {
16-
return mql.matches;
22+
function isSmallerThanBreakpoint(): boolean {
23+
return mql?.matches ?? false;
24+
}
25+
26+
function getServerSnapshot(): boolean {
27+
return false;
1728
}
1829

19-
export function useIsMobile() {
20-
return useSyncExternalStore(mediaQueryListener, isSmallerThanBreakpoint);
30+
export function useIsMobile(): boolean {
31+
return useSyncExternalStore(
32+
mediaQueryListener,
33+
isSmallerThanBreakpoint,
34+
getServerSnapshot
35+
);
2136
}

0 commit comments

Comments
 (0)