Skip to content

Instantly share code, notes, and snippets.

@danieljpgo
Last active February 29, 2024 17:27
Show Gist options
  • Save danieljpgo/a66e234fd4120d03fa27c6c8a12b93c7 to your computer and use it in GitHub Desktop.
Save danieljpgo/a66e234fd4120d03fa27c6c8a12b93c7 to your computer and use it in GitHub Desktop.
const breakpoints = {
sm: '640px',
md: '768px',
lg: '1024px',
xl: '1280px',
} as const;
type Breakpoints = keyof typeof breakpoints;
export function useMediaQuery(query: Breakpoints) {
const [matches, setMatches] = React.useState(false);
useIsomorphicLayoutEffect(() => {
const mediaQuery = window.matchMedia(`(min-width: ${breakpoints[query]})`);
setMatches(mediaQuery.matches);
mediaQuery.addEventListener('change', (event) => {
setMatches(event.matches);
});
return () =>
mediaQuery.removeEventListener('change', (event) => {
setMatches(event.matches);
});
}, [query]);
return matches;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment