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.
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}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.
Yes. Pass '(prefers-color-scheme: dark)' as the query to detect the user's system dark mode preference.
The initial value will be false on the server. The hook updates on the client after hydration. Use suppressHydrationWarning if needed.
Yes. Call useMediaQuery multiple times with different query strings, one per breakpoint or feature you need.
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.
Organise your team's code snippets with Snippetly. Share knowledge and boost productivity across your organisation.