Skip to main content

useMediaQuery

// Implement a useMediaQuery hook that subscribes and responds to media query changes (e.g. screen size, resolution, orientation, etc.).

/**
* @param {string} query
* @returns {boolean}
*/
import {useEffect, useState} from 'react';

export default function useMediaQuery(query) {
const getInitialValue = () => {
if (typeof window === 'undefined' || typeof window.matchMedia !== 'function') {
return false;
}
return window.matchMedia(query).matches;
};

const [matches, setMatches] = useState(getInitialValue);

useEffect(() => {
if (typeof window === 'undefined' || typeof window.matchMedia !== 'function') {
return undefined;
}

const media = window.matchMedia(query);
const updateMatches = () => {
setMatches(window.matchMedia(query).matches);
};

setMatches(media.matches);

const listener = () => updateMatches();

if (typeof media.addEventListener === 'function') {
media.addEventListener('change', listener);
} else {
media.addListener(listener);
}

return () => {
if (typeof media.removeEventListener === 'function') {
media.removeEventListener('change', listener);
} else {
media.removeListener(listener);
}
};
}, [query]);

return matches;
}

/**
* export default function Component() {
const isSmallDevice = useMediaQuery('only screen and (max-width: 768px)');

return <div>{isSmallDevice && <a href="#">Menu</a>}</div>;
}
*/