Current viewport

Desktop
Tablet
Mobile
Try resizing your browser window to see the changes
0 × 0

useMediaQuery

A React hook that tracks the state of a CSS media query, allowing for responsive logic in your components.

  • Create responsive components that adapt to changing viewport sizes
  • Supports all standard CSS media queries (width, orientation, dark mode, etc.)
  • Efficient updates on window resize or device orientation changes

Installation

The useMediaQuery hook is part of our UI library. You can import it directly from the hooks directory.


Usage

Here is how to use the useMediaQuery hook in your project:

React TSX
1import { useMediaQuery } from "@/hooks/use-media-query"

React TSX
1function Demo() {
2  const isDesktop = useMediaQuery("(min-width: 1024px)")
3  
4  return (
5    <div>
6      <p>Current viewport: {isDesktop ? "Desktop" : "Mobile"}</p>
7      {isDesktop ? (
8        <p>Desktop-specific content</p>
9      ) : (
10        <p>Mobile-specific content</p>
11      )}
12    </div>
13  )
14}

API Reference

React TSX
1function useMediaQuery(
2  query: string
3): boolean

Inputs

  • query: A CSS media query string to evaluate

Output

  • matches: A boolean representing whether the media query matches or not

Behavior

  • Hook evaluates the provided media query using window.matchMedia
  • Returns a boolean indicating whether the query matches
  • Re-evaluates when the window size changes or orientation changes
  • Cleans up event listeners on component unmount

Implementation

React TSX
1import { useState, useEffect } from "react"
2
3export function useMediaQuery(query: string): boolean {
4  // Initialize with a default value (consider SSR where window is not available)
5  const [matches, setMatches] = useState(false)
6  
7  useEffect(() => {
8    // Make sure we're in a browser environment
9    if (typeof window !== "undefined") {
10      // Create media query list
11      const media = window.matchMedia(query)
12      
13      // Set the initial value
14      setMatches(media.matches)
15      
16      // Define a callback to handle changes
17      const listener = (event: MediaQueryListEvent) => {
18        setMatches(event.matches)
19      }
20      
21      // Add the listener
22      if (media.addEventListener) {
23        media.addEventListener("change", listener)
24      } else {
25        // For older browsers
26        media.addListener(listener)
27      }
28      
29      // Clean up
30      return () => {
31        if (media.removeEventListener) {
32          media.removeEventListener("change", listener)
33        } else {
34          // For older browsers
35          media.removeListener(listener)
36        }
37      }
38    }
39    
40    // Empty dependency for server-side rendering
41    return undefined
42  }, [query])
43  
44  return matches
45}