Created
February 22, 2023 15:56
-
-
Save stavros-melidoniotis/6fc8ebff3297d68a94f794598844dc09 to your computer and use it in GitHub Desktop.
React hook for easy retrieval of media dimensions
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
import { useState, useEffect } from "react"; | |
const useMediaQuery = (query: string) => { | |
const [matches, setMatches] = useState(false); | |
useEffect(() => { | |
const media = window.matchMedia(query); | |
if (media.matches !== matches) { | |
setMatches(media.matches); | |
} | |
const listener = () => setMatches(media.matches); | |
window.addEventListener("resize", listener); | |
return () => window.removeEventListener("resize", listener); | |
}, [matches, query]); | |
return matches; | |
}; | |
export default useMediaQuery; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment