useMedia.tsx 786 B

123456789101112131415161718192021222324252627282930313233343536373839
  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. const [state, setState] = useState(
  7. () => window.matchMedia && window.matchMedia(query)?.matches
  8. );
  9. useEffect(() => {
  10. let mounted = true;
  11. if (!window.matchMedia) {
  12. return undefined;
  13. }
  14. const mql = window.matchMedia(query);
  15. const onChange = () => {
  16. if (!mounted) {
  17. return;
  18. }
  19. setState(!!mql.matches);
  20. };
  21. mql.addEventListener('change', onChange);
  22. setState(mql.matches);
  23. return () => {
  24. mounted = false;
  25. mql.removeEventListener('change', onChange);
  26. };
  27. }, [query]);
  28. if (!window.matchMedia) {
  29. return false;
  30. }
  31. return state;
  32. }