Created
August 1, 2022 05:10
-
-
Save iam-rohid/131aa011ae245dd969558624e4e99aec to your computer and use it in GitHub Desktop.
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 { useCallback, useEffect, useState } from "react"; | |
| const useMediaQuery = ( | |
| query: string, | |
| onChange?: (event: MediaQueryListEvent) => void | |
| ) => { | |
| const [state, setState] = useState(false); | |
| const onMediaChange = useCallback( | |
| (ev: MediaQueryListEvent) => { | |
| setState(ev.matches); | |
| onChange && onChange(ev); | |
| }, | |
| [onChange] | |
| ); | |
| useEffect(() => { | |
| if (typeof window !== undefined) { | |
| setState(window?.matchMedia(query).matches); | |
| } | |
| }, [query]); | |
| useEffect(() => { | |
| const media = window.matchMedia(query); | |
| media.addEventListener("change", onMediaChange); | |
| return () => { | |
| media.removeEventListener("change", onMediaChange); | |
| }; | |
| }, [onMediaChange, query]); | |
| return state; | |
| }; | |
| export default useMediaQuery; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment