diff --git a/resources/js/hooks/use-mobile.tsx b/resources/js/hooks/use-mobile.tsx index 710ad6e1a..2f3f531b8 100644 --- a/resources/js/hooks/use-mobile.tsx +++ b/resources/js/hooks/use-mobile.tsx @@ -2,9 +2,16 @@ import { useSyncExternalStore } from 'react'; const MOBILE_BREAKPOINT = 768; -const mql = window.matchMedia(`(max-width: ${MOBILE_BREAKPOINT - 1}px)`); +const mql = + typeof window === 'undefined' + ? undefined + : window.matchMedia(`(max-width: ${MOBILE_BREAKPOINT - 1}px)`); function mediaQueryListener(callback: (event: MediaQueryListEvent) => void) { + if (!mql) { + return () => {}; + } + mql.addEventListener('change', callback); return () => { @@ -12,10 +19,18 @@ function mediaQueryListener(callback: (event: MediaQueryListEvent) => void) { }; } -function isSmallerThanBreakpoint() { - return mql.matches; +function isSmallerThanBreakpoint(): boolean { + return mql?.matches ?? false; +} + +function getServerSnapshot(): boolean { + return false; } -export function useIsMobile() { - return useSyncExternalStore(mediaQueryListener, isSmallerThanBreakpoint); +export function useIsMobile(): boolean { + return useSyncExternalStore( + mediaQueryListener, + isSmallerThanBreakpoint, + getServerSnapshot + ); }