useMedia.tsx 665 B

123456789101112131415161718192021222324252627282930313233
  1. import {useEffect, useState} from 'react';
  2. /**
  3. * Hook that updates when a media query result changes
  4. */
  5. export default function useMedia(query: string) {
  6. if (!window.matchMedia) {
  7. return false;
  8. }
  9. const [state, setState] = useState(() => window.matchMedia(query).matches);
  10. useEffect(() => {
  11. let mounted = true;
  12. const mql = window.matchMedia(query);
  13. const onChange = () => {
  14. if (!mounted) {
  15. return;
  16. }
  17. setState(!!mql.matches);
  18. };
  19. mql.addListener(onChange);
  20. setState(mql.matches);
  21. return () => {
  22. mounted = false;
  23. mql.removeListener(onChange);
  24. };
  25. }, [query]);
  26. return state;
  27. }