fix: make useIsMobile hook and utility functions SSR-safe

- Refactor use-mobile.tsx to use getServerSnapshot for SSR
- Add window guard to consoleDebug in debug.ts
- Add window guard to isLocalEnvironment in track-event.ts
This commit is contained in:
Víctor Falcón 2025-12-08 17:33:54 +01:00
parent 30d64f8249
commit 40762bc528
3 changed files with 22 additions and 11 deletions

View File

@ -2,20 +2,28 @@ import { useSyncExternalStore } from 'react';
const MOBILE_BREAKPOINT = 768;
const mql = window.matchMedia(`(max-width: ${MOBILE_BREAKPOINT - 1}px)`);
function mediaQueryListener(callback: (event: MediaQueryListEvent) => void) {
mql.addEventListener('change', callback);
return () => {
mql.removeEventListener('change', callback);
};
function getMediaQueryList(): MediaQueryList | null {
if (typeof window === 'undefined') return null;
return window.matchMedia(`(max-width: ${MOBILE_BREAKPOINT - 1}px)`);
}
function isSmallerThanBreakpoint() {
return mql.matches;
function subscribe(callback: () => void) {
const mql = getMediaQueryList();
if (!mql) return () => {};
mql.addEventListener('change', callback);
return () => mql.removeEventListener('change', callback);
}
function getSnapshot() {
const mql = getMediaQueryList();
return mql ? mql.matches : false;
}
function getServerSnapshot() {
return false;
}
export function useIsMobile() {
return useSyncExternalStore(mediaQueryListener, isSmallerThanBreakpoint);
return useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);
}

View File

@ -1,4 +1,6 @@
export function consoleDebug(...args: unknown[]): void {
if (typeof window === 'undefined') return;
const isDebugEnabled = localStorage.getItem('debug') === 'true';
const isLocalhost = window.location.hostname === 'localhost';
const isTestDomain = window.location.hostname.includes('.test');

View File

@ -12,6 +12,7 @@ export interface TrackEventOptions {
}
function isLocalEnvironment(): boolean {
if (typeof window === 'undefined') return true;
const hostname = window.location.hostname;
return hostname === 'localhost' || hostname.endsWith('.test');
}