← Back to all snippets
JAVASCRIPT

Dynamically Respond to CSS Media Queries with React's `useMediaQuery`

Build a `useMediaQuery` hook to reactively apply JavaScript logic based on CSS media queries, enabling truly responsive UI components in React applications.

import { useState, useEffect } from 'react';

function useMediaQuery(query) {
  const [matches, setMatches] = useState(false);

  useEffect(() => {
    if (typeof window !== 'undefined') {
      const mediaQueryList = window.matchMedia(query);
      setMatches(mediaQueryList.matches);

      const listener = (event) => setMatches(event.matches);
      mediaQueryList.addEventListener('change', listener);

      return () => {
        mediaQueryList.removeEventListener('change', listener);
      };
    }
  }, [query]);

  return matches;
}

// Example Usage:
// function ResponsiveComponent() {
//   const isLargeScreen = useMediaQuery('(min-width: 1024px)');
//   const isDarkMode = useMediaQuery('(prefers-color-scheme: dark)');

//   return (
//     <div style={{ background: isDarkMode ? '#333' : '#fff', color: isDarkMode ? '#eee' : '#333' }}>
//       <h1>{isLargeScreen ? 'Large Screen Layout' : 'Small Screen Layout'}</h1>
//       <p>Current color scheme: {isDarkMode ? 'Dark' : 'Light'}</p>
//       <p>This text adapts based on screen size and system theme preference.</p>
//     </div>
//   );
// }
How it works: The `useMediaQuery` hook allows your React components to reactively respond to CSS media queries using JavaScript. It takes a media query string (e.g., `'(min-width: 768px)'`) and returns a boolean indicating whether the query currently matches. Internally, it uses `window.matchMedia` to evaluate the query and `addEventListener` with `removeEventListener` to subscribe to changes in the media query's state. This enables dynamic styling, rendering different components, or executing specific logic based on screen size, dark mode preference, or any other media feature.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs