fix: read matchMedia synchronously on client to prevent layout flicker

This commit is contained in:
Linus Rath
2026-04-21 23:02:21 +02:00
parent f9aa5cbaee
commit 361ad49f5f
+20 -16
View File
@@ -1,6 +1,6 @@
"use client"; "use client";
import { useState, useEffect } from "react"; import { useCallback, useEffect, useSyncExternalStore } from "react";
import { useUIStore } from "@/stores/ui-store"; import { useUIStore } from "@/stores/ui-store";
// Tailwind v4 breakpoints // Tailwind v4 breakpoints
@@ -12,26 +12,30 @@ const BREAKPOINTS = {
"2xl": 1536, "2xl": 1536,
} as const; } as const;
const getMediaQueryServerSnapshot = () => false;
/** /**
* SSR-safe media query hook * SSR-safe media query hook. On SSR and the first hydration pass we report
* Returns false during SSR to prevent hydration mismatch * `false`; on all subsequent client renders (including client-side navigation
* remounts) we read `matchMedia` synchronously, so components don't flash
* through a one-frame "mobile" layout on desktop.
*/ */
export function useMediaQuery(query: string): boolean { export function useMediaQuery(query: string): boolean {
const [matches, setMatches] = useState(false); const subscribe = useCallback(
(callback: () => void) => {
const mq = window.matchMedia(query);
mq.addEventListener("change", callback);
return () => mq.removeEventListener("change", callback);
},
[query],
);
useEffect(() => { const getSnapshot = useCallback(
const mediaQuery = window.matchMedia(query); () => window.matchMedia(query).matches,
setMatches(mediaQuery.matches); [query],
);
const handler = (event: MediaQueryListEvent) => { return useSyncExternalStore(subscribe, getSnapshot, getMediaQueryServerSnapshot);
setMatches(event.matches);
};
mediaQuery.addEventListener("change", handler);
return () => mediaQuery.removeEventListener("change", handler);
}, [query]);
return matches;
} }
/** /**