Created
November 23, 2022 17:59
-
-
Save davidmc971/da8429d6876418539447508b2351d4c5 to your computer and use it in GitHub Desktop.
Custom media query hook in React
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 { useEffect, useRef, useState } from "react"; | |
| const useMediaQuery = (minWidth, maxWidth) => { | |
| const mediaQuery = "screen".concat( | |
| minWidth !== undefined ? ` and (min-width: ${minWidth})` : "", | |
| maxWidth !== undefined ? ` and (max-width: ${maxWidth})` : "" | |
| ); | |
| const [matches, setMatches] = useState(window.matchMedia(mediaQuery).matches); | |
| const listenerAdded = useRef(false); | |
| useEffect(() => { | |
| if (listenerAdded.current) return; | |
| window | |
| .matchMedia(mediaQuery) | |
| .addEventListener("change", (e) => setMatches(e.matches)); | |
| listenerAdded.current = true; | |
| }, [mediaQuery]); | |
| return matches; | |
| }; | |
| export default useMediaQuery; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment