useMedia.ts 506 B

123456789101112131415161718192021
  1. import { useEffect, useState } from "react";
  2. export const useMedia = (query: string) => {
  3. const [match, setMatch] = useState(window.matchMedia(query));
  4. useEffect(() => {
  5. const handleWindowResize = () => {
  6. setMatch(window.matchMedia(query));
  7. };
  8. window.addEventListener("resize", handleWindowResize);
  9. return () => window.removeEventListener("resize", handleWindowResize);
  10. }, []);
  11. useEffect(() => {
  12. setMatch(window.matchMedia(query));
  13. }, [query]);
  14. return match;
  15. };