Skip to content

Instantly share code, notes, and snippets.

@iam-rohid
Created August 1, 2022 05:10
Show Gist options
  • Select an option

  • Save iam-rohid/131aa011ae245dd969558624e4e99aec to your computer and use it in GitHub Desktop.

Select an option

Save iam-rohid/131aa011ae245dd969558624e4e99aec to your computer and use it in GitHub Desktop.
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