From cdc15ef488fe20e6b3644e215ada8713885dac62 Mon Sep 17 00:00:00 2001 From: Nico <47644445+nicotsx@users.noreply.github.com> Date: Tue, 3 Mar 2026 21:27:22 +0100 Subject: [PATCH] fix(use-mobile): use sync external storage to wait before initial render (#610) --- app/client/hooks/use-mobile.ts | 30 ++++++++++++++++-------------- 1 file changed, 16 insertions(+), 14 deletions(-) diff --git a/app/client/hooks/use-mobile.ts b/app/client/hooks/use-mobile.ts index 21e5c1f0..8b812788 100644 --- a/app/client/hooks/use-mobile.ts +++ b/app/client/hooks/use-mobile.ts @@ -2,18 +2,20 @@ import * as React from "react"; const MOBILE_BREAKPOINT = 768; -export function useIsMobile() { - const [isMobile, setIsMobile] = React.useState(undefined); - - React.useEffect(() => { - const mql = window.matchMedia(`(max-width: ${MOBILE_BREAKPOINT - 1}px)`); - const onChange = () => { - setIsMobile(window.innerWidth < MOBILE_BREAKPOINT); - }; - mql.addEventListener("change", onChange); - setIsMobile(window.innerWidth < MOBILE_BREAKPOINT); - return () => mql.removeEventListener("change", onChange); - }, []); - - return !!isMobile; +function subscribe(callback: () => void) { + const mql = window.matchMedia(`(max-width: ${MOBILE_BREAKPOINT - 1}px)`); + mql.addEventListener("change", callback); + return () => mql.removeEventListener("change", callback); +} + +function getSnapshot() { + return window.innerWidth < MOBILE_BREAKPOINT; +} + +function getServerSnapshot() { + return false; +} + +export function useIsMobile() { + return React.useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot); }