How to create a custom hook for handling media queries in React



Image not found!!

Creating a custom hook for handling media queries in React can be a useful way to manage responsive behavior in your components. Here's a simple example of how you can create a custom hook for handling media queries:

jsx
import { useState, useEffect } from 'react'; const useMediaQuery = (query) => { const [matches, setMatches] = useState(false); useEffect(() => { const mediaQuery = window.matchMedia(query); const handleMediaChange = (event) => { setMatches(event.matches); }; // Initial check setMatches(mediaQuery.matches); // Add listener for changes mediaQuery.addListener(handleMediaChange); // Clean up listener on component unmount return () => { mediaQuery.removeListener(handleMediaChange); }; }, [query]); return matches; }; export default useMediaQuery;

This hook uses the window.matchMedia method to check whether a media query matches the current window size. It then sets up an event listener to track changes in the match status. The hook returns the current match status, allowing you to conditionally render components or apply styles based on the media query result.

Here's an example of how you might use this custom hook in a component:

jsx
import React from 'react'; import useMediaQuery from './useMediaQuery'; const MyComponent = () => { const isSmallScreen = useMediaQuery('(max-width: 600px)'); return ( <div> {isSmallScreen ? ( <p>This is a small screen.</p> ) : ( <p>This is not a small screen.</p> )} </div> ); }; export default MyComponent;

In this example, MyComponent uses the useMediaQuery hook to check if the screen width is less than or equal to 600 pixels. The component then renders different content based on the result of the media query.