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}
* 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()


You should install a polyfill just in case:

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(),


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


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