Back to all snippets
Library/React/useMediaQuery Hook
typescriptintermediatehooksresponsiveui

How to implement useMediaQuery Hook in Typescript

React hook for responsive design with CSS media queries

Quick Answer

useMediaQuery subscribes to a CSS media query string and returns a reactive boolean. The component automatically re-renders when the screen crosses the breakpoint — no manual resize listeners needed.

Code Snippet

1import { useState, useEffect } from 'react';
2
3function useMediaQuery(query: string): boolean {
4  const [matches, setMatches] = useState(false);
5
6  useEffect(() => {
7    const media = window.matchMedia(query);
8    if (media.matches !== matches) {
9      setMatches(media.matches);
10    }
11    const listener = () => setMatches(media.matches);
12    media.addEventListener('change', listener);
13    return () => media.removeEventListener('change', listener);
14  }, [matches, query]);
15
16  return matches;
17}

What is useMediaQuery Hook?

useMediaQuery subscribes to a CSS media query and returns a boolean that updates whenever the match status changes. This lets you conditionally render or style components based on screen size, motion preferences, color scheme, and any other media feature — all in a reactive, hook-based API.

How It Works

  1. 1window.matchMedia(query) creates a MediaQueryList that tracks the query.
  2. 2The initial match state is read synchronously before the first render.
  3. 3An event listener on the MediaQueryList updates state when the match changes.
  4. 4The listener is removed in the useEffect cleanup to prevent memory leaks.

Common Use Cases

  • Conditional rendering - Show different components on mobile vs desktop
  • Prefers-reduced-motion - Disable animations for accessibility
  • Dark mode detection - Read system color scheme preference
  • Print styles - Adjust UI when user triggers print

Key Benefits

  • Reactive — component re-renders automatically on breakpoint change
  • Supports any CSS media query string
  • Properly removes the event listener on unmount
  • No external library required

Common Mistakes to Avoid

  • Hardcoding breakpoints as magic numbers — export constants so they stay in sync with CSS.
  • Using window.innerWidth in useEffect instead — that requires manual resize listeners and is less accurate.
  • Not handling SSR — window is undefined on the server; initialise matches to false and hydrate on the client.

Quick Tips

  • Click the "Copy" button above to copy the code to your clipboard
  • This code is production-ready and can be used in your projects immediately
  • Check out related snippets below for more typescript examples

Frequently Asked Questions

Can useMediaQuery detect dark mode preference?

Yes. Pass '(prefers-color-scheme: dark)' as the query to detect the user's system dark mode preference.

Does useMediaQuery work in Next.js with SSR?

The initial value will be false on the server. The hook updates on the client after hydration. Use suppressHydrationWarning if needed.

Can I use multiple media queries in one component?

Yes. Call useMediaQuery multiple times with different query strings, one per breakpoint or feature you need.

About This Typescript Code Snippet

This free typescript code snippet for usemediaquery hook is production-ready and copy-paste friendly. Whether you are building a web app, API, or frontend interface, this intermediate-level example will help you implement usemediaquery hook quickly and correctly.

All snippets in the Snippetly library follow typescript best practices and are tested for real-world use. You can adapt this code to work with React, Vue, Node.js, or any project that uses typescript.

Tags: hooks, responsive, ui  | Language: typescript  | Difficulty: intermediate  | Category: React

Build Your Own Snippet Library

Organise your team's code snippets with Snippetly. Share knowledge and boost productivity across your organisation.