ReactJS useMediaQuery hook using window.matchMedia(‘…’).

import { useEffect, useMemo, useState } from 'react'/**
* Check if a media query matches the UI
* @param {String} mediaQueryString
* @returns {Boolean}
*
* https://developer.mozilla.org/en-US/docs/Web/API/Window/matchMedia
* https://developer.mozilla.org/en-US/docs/Web/API/MediaQueryList/change_event
*
* Example:
* useMediaQuery('(max-width: 600px)');
* useMediaQuery('only screen and (min-width: 600px)');
* useMediaQuery('@media only screen and (min-width: 600px)');
*/
export function useMediaQuery(mediaQueryString) {
const queryString = removeReservedMediaKeyWord(mediaQueryString)
const query = useMemo(() => window.matchMedia(queryString), [queryString])
const [matches, setMatches] = useState(query.matches) // one-time, instantaneous check
useEffect(() => {
const listener = (e) => setMatches(e.matches)
query.addEventListener('change', listener)
return () => query.removeEventListener('change', listener)
}, [query])
return matches
}
function removeReservedMediaKeyWord(mediaQueryString) {
return mediaQueryString.replace('@media', '').trim()
}

Polyfill

You should install a polyfill just in case: https://www.npmjs.com/package/matchmedia-polyfill.

Testing in Jest

Object.defineProperty(window, 'matchMedia', {
writable: true,
value: jest.fn().mockImplementation(query => ({
matches: false,
media: query,
onchange: null,
addListener: jest.fn(), // deprecated
removeListener: jest.fn(), // deprecated
addEventListener: jest.fn(),
removeEventListener: jest.fn(),
dispatchEvent: jest.fn(),
})),
});

Related

Might also interest you; a list of media queries that I found useful with CSS in JS and are based on Bootstrap V5 breakpoint sizes:

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Pablo Garcia

Pablo Garcia

30 Followers

Staff Engineer @PayPal, M.S. in Computer Science w/specialization in Computing Systems, B.Eng. in Computer Software.