Frontend Blocks typescript Intermediate

useMediaQuery Hook

React hook that returns true when a CSS media query matches.

typescript
import { useState, useEffect } from 'react';
export function useMediaQuery(query) {
  const [matches, setMatches] = useState(false);
  useEffect(() => {
    const mq = window.matchMedia(query);
    setMatches(mq.matches);
    const handler = (e) => setMatches(e.matches);
    mq.addEventListener('change', handler);
    return () => mq.removeEventListener('change', handler);
  }, [query]);
  return matches;
}

Prerequisites

  • React >= 17

Pro Tips

  • → Use for responsive logic that CSS alone cannot handle.

Was this module useful?

Share your experience — it helps the team improve.

Leave Feedback

Commercial Licensing

Acquire a production access token or template license for enterprise deployment.

Module Info

Language
typescript
Level
Intermediate
Read time
2 min
Published
Nov 2024
License
Commercial License

Newsletter

New modules every week, directly to your inbox.