Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 15 additions & 6 deletions resources/js/hooks/use-mobile.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,20 +2,29 @@ import { useSyncExternalStore } from 'react';

const MOBILE_BREAKPOINT = 768;

const mql = window.matchMedia(`(max-width: ${MOBILE_BREAKPOINT - 1}px)`);
const mql = (): MediaQueryList | null => {
if (typeof window === 'undefined') return null;
return window.matchMedia(`(max-width: ${MOBILE_BREAKPOINT - 1}px)`);
};

function mediaQueryListener(callback: (event: MediaQueryListEvent) => void) {
mql.addEventListener('change', callback);
mql()?.addEventListener('change', callback);

return () => {
mql.removeEventListener('change', callback);
mql()?.removeEventListener('change', callback);
};
}

function isSmallerThanBreakpoint() {
return mql.matches;
function isSmallerThanBreakpoint(): boolean {
return mql()?.matches || false;
}

const getServerSnapshot = (): boolean => false;

export function useIsMobile() {
return useSyncExternalStore(mediaQueryListener, isSmallerThanBreakpoint);
return useSyncExternalStore(
mediaQueryListener,
isSmallerThanBreakpoint,
getServerSnapshot,
);
}