Shane Jix

[Snippet] - useMediaQuery

create:December 09, 2021  update:April 12, 2022  ☕️ 1 min read

同步链接: https://www.shanejix.com/posts/[Snippet] - useMediaQuery/

import { useState, useEffect } from "react";

export function 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);
    };

    media.addListener(listener);

    return () => media.removeListener(listener);
  }, [matches, query]);

  return matches;
}

usage:

function Page() {
  let isPageWide = useMediaQuery("(min-width: 800px)");

  return (
    <>
      {isPageWide && <UnnecessarySidebar />}
      <ImportantContent />
    </>
  );
}

作者:shanejix 出处:https://www.shanejix.com/posts/[Snippet] - useMediaQuery/ 版权:本作品采用「署名-非商业性使用-相同方式共享 4.0 国际」许可协议进行许可。 声明:转载请注明出处!

Edit on GitHubDiscuss on GitHub


Shane Jix

Personal blog by Shane Jix. I explain with words and code.

LinksTools
© 2019 - 2022, Built withGatsby