From 21c8da709fe3d206f24f3bd402fdfa42dc6c4b5c Mon Sep 17 00:00:00 2001 From: Sampo Juustila Date: Wed, 24 Sep 2025 09:12:24 +0300 Subject: [PATCH] Fix iframe support in useMatchMedia (#114) * Fix iframe support in useMatchMedia Closes #112 --------- Co-authored-by: Sampo Juustila Co-authored-by: Wojciech Maj --- src/useMatchMedia.ts | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/src/useMatchMedia.ts b/src/useMatchMedia.ts index 9d570f4..c3676eb 100644 --- a/src/useMatchMedia.ts +++ b/src/useMatchMedia.ts @@ -1,4 +1,4 @@ -import { useCallback, useEffect, useMemo, useState } from 'react'; +import { useCallback, useEffect, useState } from 'react'; const isBrowser = typeof window !== 'undefined'; @@ -9,18 +9,21 @@ const isBrowser = typeof window !== 'undefined'; * @returns {boolean | null} Whether the document matches the given media query string */ export default function useMatchMedia(query: string): boolean | null { - const mql = useMemo(() => (isBrowser ? window.matchMedia(query) : null), [query]); - const [matches, setMatches] = useState(mql ? mql.matches : null); + const [matches, setMatches] = useState(() => + isBrowser ? window.matchMedia(query).matches : null, + ); const handleMql = useCallback((event: MediaQueryListEvent) => { setMatches(event.matches); }, []); useEffect(() => { - if (!mql) { + if (!isBrowser) { return undefined; } + const mql = window.matchMedia(query); + if (mql.addEventListener) { mql.addEventListener('change', handleMql); @@ -34,7 +37,7 @@ export default function useMatchMedia(query: string): boolean | null { mql.removeListener(handleMql); }; } - }, [mql, handleMql]); + }, [query, handleMql]); return matches; } -- 2.51.2