JAVASCRIPT

Dynamically Respond to CSS Media Queries with useMediaQuery

Implement a React hook, useMediaQuery, to dynamically detect and respond to CSS media query changes, enabling responsive component rendering.

import { useState, useEffect } from 'react';

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

  useEffect(() => {
    const mediaQuery = window.matchMedia(query);
    setMatches(mediaQuery.matches); // Set initial state

    const handler = (event) => setMatches(event.matches);
    mediaQuery.addEventListener('change', handler);

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

  return matches;
}

export default useMediaQuery;
How it works: The useMediaQuery hook listens for changes in a specified CSS media query. It initializes its state based on the current match and then adds an event listener to update the state whenever the media query's status changes. This allows components to re-render or adjust their content and layout dynamically based on responsive breakpoints, providing a powerful way to manage responsive UIs in React.

Need help integrating this into your project?

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

Hire DigitalCodeLabs