Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVASCRIPT

useMediaQuery react hook

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;

// using the hook
const isDesktop = useMediaQuery('(min-width: 960px)');
Source by fireship.io #
 
PREVIOUS NEXT
Tagged: #useMediaQuery #react #hook
ADD COMMENT
Topic
Name
9+2 =