Last active
February 29, 2024 17:27
-
-
Save danieljpgo/a66e234fd4120d03fa27c6c8a12b93c7 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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