useMediaQuery Hook in React
A reusable custom hook for detecting responsive breakpoints, dark mode preferences, and media query matches directly inside React components.
Why use a media query hook?
Responsive design is not only about CSS. In many cases, you also need to change component behavior, conditional rendering, or app logic based on screen size or user preferences. A custom hook makes this logic reusable and easy to manage.
What this hook does
This useMediaQuery hook checks whether a given media query matches the current environment, listens for changes, and updates your component automatically when the result changes.
The Hook
Here is the full source code:
import { useEffect, useState } from "react";export function useMediaQuery(query: string): boolean {const getMatches = () => {if (typeof window === "undefined") return false;return window.matchMedia(query).matches;};const [matches, setMatches] = useState(getMatches);useEffect(() => {if (typeof window === "undefined") return;const mediaQueryList = window.matchMedia(query);const updateMatches = () => {setMatches(mediaQueryList.matches);};updateMatches();if (mediaQueryList.addEventListener) {mediaQueryList.addEventListener("change", updateMatches);return () => mediaQueryList.removeEventListener("change", updateMatches);} else {// Fallback for older browsersmediaQueryList.addListener(updateMatches);return () => mediaQueryList.removeListener(updateMatches);}}, [query]);return matches;}
Quick Examples
You can use this hook for different responsive use cases:
const isMobile = useMediaQuery("(max-width: 768px)");const prefersDark = useMediaQuery("(prefers-color-scheme: dark)");const isDesktop = useMediaQuery("(min-width: 1024px)");
Usage Example
Here is a simple component that renders different content on mobile and desktop:
import React from "react";import { useMediaQuery } from "./useMediaQuery";export default function ResponsiveBanner() {const isMobile = useMediaQuery("(max-width: 768px)");return (<div>{isMobile ? (<p>This text is only shown on mobile devices.</p>) : (<p>This text is shown on desktop screens.</p>)}</div>);}
Key Benefits
- Reusable: Centralizes responsive logic in one hook.
- Reactive: Automatically updates when the media query result changes.
- Flexible: Useful for breakpoints, dark mode, reduced motion, and more.
FAQ
Why use a custom media query hook in React?
It helps you keep responsive logic inside React components without repeating the same matchMedia setup everywhere.
Can I use it for dark mode detection?
Yes. A query like (prefers-color-scheme: dark) works perfectly for detecting system theme preferences.
Is there support for older browsers?
Yes. The hook uses addEventListener when available and falls back to addListener for compatibility.