JAVASCRIPT

Adapt UI to CSS Media Queries with React Hook

Develop a `useMediaQuery` React hook to detect if a specific CSS media query matches, enabling dynamic and responsive component rendering based on screen size.

import { useState, useEffect } from 'react';

function useMediaQuery(query) {
  const [matches, setMatches] = useState(() => window.matchMedia(query).matches);

  useEffect(() => {
    const mediaQueryList = window.matchMedia(query);
    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)');

//   return (
//     <div>
//       {isLargeScreen ? (
//         <h1>Welcome to the large screen layout!</h1>
//       ) : (
//         <h2>Welcome to the small screen layout!</h2>
//       )}
//       <p>Current screen size: {isLargeScreen ? 'Large' : 'Small'}</p>
//     </div>
//   );
// }
How it works: This `useMediaQuery` hook listens for changes to a given CSS media query and returns a boolean indicating whether the query currently matches. It leverages the `window.matchMedia` API to provide real-time responsiveness, allowing React components to dynamically adjust their rendering or behavior based on screen size, orientation, or other media features without relying solely on CSS.

Need help integrating this into your project?

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

Hire DigitalCodeLabs