Created
May 17, 2022 15:01
-
-
Save mmaous/df5dbfea78a6182b6bb989eb0ce46e49 to your computer and use it in GitHub Desktop.
Easily retrieve media dimensions with this Hook React which also works onResize.
This file contains hidden or 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) => { | |
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