diff --git a/packages/mui-material/src/useMediaQuery/useMediaQuery.test.js b/packages/mui-material/src/useMediaQuery/useMediaQuery.test.js index cc76df77055a75..07857d97f75869 100644 --- a/packages/mui-material/src/useMediaQuery/useMediaQuery.test.js +++ b/packages/mui-material/src/useMediaQuery/useMediaQuery.test.js @@ -22,11 +22,10 @@ function createMatchMedia(width, ref) { matches: mediaQuery.match(query, { width, }), - // Mocking matchMedia in Safari < 14 where MediaQueryList doesn't inherit from EventTarget - addListener: (listener) => { + addEventListener: (eventType, listener) => { listeners.push(listener); }, - removeListener: (listener) => { + removeEventListener: (eventType, listener) => { const index = listeners.indexOf(listener); if (index > -1) { listeners.splice(index, 1); diff --git a/packages/mui-system/src/useMediaQuery/useMediaQuery.ts b/packages/mui-system/src/useMediaQuery/useMediaQuery.ts index 592785aece184b..fa2d546ae1879c 100644 --- a/packages/mui-system/src/useMediaQuery/useMediaQuery.ts +++ b/packages/mui-system/src/useMediaQuery/useMediaQuery.ts @@ -72,27 +72,20 @@ function useMediaQueryOld( }); useEnhancedEffect(() => { - let active = true; - if (!matchMedia) { return undefined; } const queryList = matchMedia!(query); const updateMatch = () => { - // Workaround Safari wrong implementation of matchMedia - // TODO can we remove it? - // https://github.com/mui/material-ui/pull/17315#issuecomment-528286677 - if (active) { - setMatch(queryList.matches); - } + setMatch(queryList.matches); }; + updateMatch(); - // TODO: Use `addEventListener` once support for Safari < 14 is dropped - queryList.addListener(updateMatch); + queryList.addEventListener('change', updateMatch); + return () => { - active = false; - queryList.removeListener(updateMatch); + queryList.removeEventListener('change', updateMatch); }; }, [query, matchMedia]); @@ -131,10 +124,9 @@ function useMediaQueryNew( return [ () => mediaQueryList.matches, (notify: () => void) => { - // TODO: Use `addEventListener` once support for Safari < 14 is dropped - mediaQueryList.addListener(notify); + mediaQueryList.addEventListener('change', notify); return () => { - mediaQueryList.removeListener(notify); + mediaQueryList.removeEventListener('change', notify); }; }, ];