Skip to content

Instantly share code, notes, and snippets.

@bfodeke
Created July 6, 2021 15:49
Show Gist options
  • Save bfodeke/aad4d8e0651e6a36130b73bb5e7c9b87 to your computer and use it in GitHub Desktop.
Save bfodeke/aad4d8e0651e6a36130b73bb5e7c9b87 to your computer and use it in GitHub Desktop.
React mediaquery hook
import { useState, useEffect } from 'react';
export function useMediaQuery(query) {
const [matches, setMatches] = useState(false);
useEffect(() => {
const media: MediaQueryList = window.matchMedia(query);
if (media.matches !== matches) {
setMatches(media.matches);
}
const listener = () => {
setMatches(media.matches);
};
media.addEventListener('change', listener);
return () => media.removeEventListener('change', listener);
}, [matches, query]);
return matches;
}
@bfodeke
Copy link
Author

bfodeke commented Jul 6, 2021

Usage

import { useMediaQuery } from '../Hooks/mediaquery.hook';

const App = () => {
  const isMobileWidth = useMediaQuery('(max-width: 767px)');
}

export default App;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment