fix(use-mobile): use sync external storage to wait before initial render (#610)

This commit is contained in:
Nico 2026-03-03 21:27:22 +01:00 committed by GitHub
parent f511095fde
commit cdc15ef488
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -2,18 +2,20 @@ import * as React from "react";
const MOBILE_BREAKPOINT = 768; const MOBILE_BREAKPOINT = 768;
export function useIsMobile() { function subscribe(callback: () => void) {
const [isMobile, setIsMobile] = React.useState<boolean | undefined>(undefined);
React.useEffect(() => {
const mql = window.matchMedia(`(max-width: ${MOBILE_BREAKPOINT - 1}px)`); const mql = window.matchMedia(`(max-width: ${MOBILE_BREAKPOINT - 1}px)`);
const onChange = () => { mql.addEventListener("change", callback);
setIsMobile(window.innerWidth < MOBILE_BREAKPOINT); return () => mql.removeEventListener("change", callback);
}; }
mql.addEventListener("change", onChange);
setIsMobile(window.innerWidth < MOBILE_BREAKPOINT); function getSnapshot() {
return () => mql.removeEventListener("change", onChange); return window.innerWidth < MOBILE_BREAKPOINT;
}, []); }
return !!isMobile; function getServerSnapshot() {
return false;
}
export function useIsMobile() {
return React.useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);
} }