useMediaQuery

A hook to detect if a media query matches.

Overview

useMediaQuery allows you to programmatically check if the window matches a specific media query. This is useful for conditional rendering based on viewport size or device capabilities.

Demo

Responsive Check

Device Detector

Resize your window to see the hook detect changes in the viewport width.

Mobile
< 640px
Tablet
641-1024px
Desktop
> 1025px
active: Desktop

API Reference

function useMediaQuery(query: string): boolean

Parameters

NameTypeDescription
querystringThe media query string to match (e.g., (min-width: 768px)).

Usage Example

import { useMediaQuery } from 'react-hooks-ts'
 
function ResponsiveComponent() {
  const isMobile = useMediaQuery('(max-width: 768px)')
 
  return (
    <div>
      {isMobile ? 'Mobile View' : 'Desktop View'}
    </div>
  )
}