ReactJs useMediaQuery hook
17 Апреля 2022
export const useMediaQuery = (query: string, initialState = false): boolean => {
const [matches, setMatches] = useState(initialState);
useEffect(() => {
if (typeof window === 'undefined' || typeof window.matchMedia === 'undefined') {
return;
}
const media: MediaQueryList = window.matchMedia(query);
const listener = () => {
setMatches(media.matches);
};
if (media.matches !== matches) {
listener();
}
media.addEventListener('change', listener);
return () => media.removeEventListener('change', listener);
}, [matches, query]);
return matches;
};