fix(use-mobile): use sync external storage to wait before initial render (#610)
This commit is contained in:
parent
f511095fde
commit
cdc15ef488
1 changed files with 16 additions and 14 deletions
|
|
@ -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);
|
const mql = window.matchMedia(`(max-width: ${MOBILE_BREAKPOINT - 1}px)`);
|
||||||
|
mql.addEventListener("change", callback);
|
||||||
React.useEffect(() => {
|
return () => mql.removeEventListener("change", callback);
|
||||||
const mql = window.matchMedia(`(max-width: ${MOBILE_BREAKPOINT - 1}px)`);
|
}
|
||||||
const onChange = () => {
|
|
||||||
setIsMobile(window.innerWidth < MOBILE_BREAKPOINT);
|
function getSnapshot() {
|
||||||
};
|
return window.innerWidth < MOBILE_BREAKPOINT;
|
||||||
mql.addEventListener("change", onChange);
|
}
|
||||||
setIsMobile(window.innerWidth < MOBILE_BREAKPOINT);
|
|
||||||
return () => mql.removeEventListener("change", onChange);
|
function getServerSnapshot() {
|
||||||
}, []);
|
return false;
|
||||||
|
}
|
||||||
return !!isMobile;
|
|
||||||
|
export function useIsMobile() {
|
||||||
|
return React.useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);
|
||||||
}
|
}
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue