Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Snippet] - useMediaQuery #83

Open
shanejix opened this issue Dec 9, 2021 · 0 comments
Open

[Snippet] - useMediaQuery #83

shanejix opened this issue Dec 9, 2021 · 0 comments

Comments

@shanejix
Copy link
Owner

shanejix commented Dec 9, 2021

同步链接: 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 国际」许可协议进行许可。
声明:转载请注明出处!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant