JAVASCRIPT

Create a `useMediaQuery` Hook for Responsive UIs

Build a custom React `useMediaQuery` hook to dynamically respond to CSS media queries, enabling adaptive UI components based on screen size or user preferences like dark mode.

import { useState, useEffect } from 'react';

// Custom hook to detect if a given media query matches
function useMediaQuery(query) {
  // State to store whether the media query currently matches
  const [matches, setMatches] = useState(false);

  useEffect(() => {
    // Check if window is defined (for SSR compatibility)
    if (typeof window === 'undefined') return;

    const mediaQueryList = window.matchMedia(query);

    // Initial check
    setMatches(mediaQueryList.matches);

    // Event listener for changes in the media query status
    const handler = (event) => setMatches(event.matches);
    mediaQueryList.addEventListener('change', handler);

    // Cleanup function to remove the event listener
    return () => {
      mediaQueryList.removeEventListener('change', handler);
    };
  }, [query]); // Re-run effect if the query string changes

  return matches;
}

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

  const screenMessage = isLargeScreen ? 'You are on a large screen.' : 'You are on a small screen.';
  const themeMessage = prefersDarkMode ? 'You prefer dark mode.' : 'You prefer light mode.';

  return (
    <div style={prefersDarkMode ? { background: '#333', color: '#fff', padding: '20px' } : { background: '#fff', color: '#333', padding: '20px' }}>
      <h1>Responsive UI Example</h1>
      <p>{screenMessage}</p>
      <p>{themeMessage}</p>
      <p>
        Adjust your browser window size or system's dark mode setting to see changes.
      </p>
    </div>
  );
}

export default ResponsiveComponent;
How it works: The `useMediaQuery` custom hook allows React components to react to CSS media query changes. It uses `window.matchMedia` to check the initial state of a given media query and then adds an event listener to update the component's state whenever the query's match status changes. The `useEffect` hook handles setting up and cleaning up the event listener, ensuring efficient and correct behavior. This hook is incredibly useful for building responsive UIs, toggling themes (like dark mode), or conditionally rendering components based on various environmental characteristics defined by media queries.

Need help integrating this into your project?

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

Hire DigitalCodeLabs