Here's how to create a useMediaQuery()
hook in React. It allows you to display components differently based on the screen size or media query:
import { useState, useEffect } from 'react';
const useMediaQuery = (query) => {
const [matches, setMatches] = useState(false);
useEffect(() => {
const mediaQuery = window.matchMedia(query);
// Update matches state when media query matches or unmatches
const handleChange = (event) => {
setMatches(event.matches);
};
// Add listener for changes to the media query
mediaQuery.addListener(handleChange);
// Set initial state
setMatches(mediaQuery.matches);
// Cleanup function to remove listener when component unmounts
return () => {
mediaQuery.removeListener(handleChange);
};
}, [query]);
return matches;
};
export default useMediaQuery;
You can use this useMediaQuery
hook in your components to conditionally render components based on the viewport size or media query. Here's how you can use it:
import React from 'react';
import useMediaQuery from './useMediaQuery'; // Assuming you've placed the hook in a separate file
const MyComponent = () => {
const isMobile = useMediaQuery('(max-width: 768px)');
return (
<div>
<h1>Media Query Example</h1>
{isMobile ? (
<p>This is a mobile device.</p>
) : (
<p>This is not a mobile device.</p>
)}
</div>
);
};
export default MyComponent;
In this example:
We create the
MyComponent
function.We use the
useMediaQuery
hook to check if the screen size is 768px wide or less.This hook gives us a true or false value (
isMobile
) based on the screen size.Depending on
isMobile
, we show a message saying either it's a mobile device or it's not.
This useMediaQuery
hook makes creating responsive designs in React components easier by removing the need to repeatedly write code for media queries. It helps in reusing code and makes components simpler and clearer.