Skip to content

Instantly share code, notes, and snippets.

@Alimjanov-Ibragim
Forked from ali-sabry/useMediaQuery.js
Created March 27, 2023 08:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Alimjanov-Ibragim/58c920a68a1b6893647e2d1b2145f91b to your computer and use it in GitHub Desktop.
Save Alimjanov-Ibragim/58c920a68a1b6893647e2d1b2145f91b to your computer and use it in GitHub Desktop.
This custom hook will allow me to easily check if the current screen size matches a specific media query (e.g., desktop or mobile). By using this hook, I can conditionally render components based on the screen size and optimize my app for different devices.
//=== Custom Hook useMediaQuery
import { useState, useEffect } from 'react';
export const useMediaQuery = (query) => {
const [matches, setMatches] = useState(false);
useEffect(() => {
const mediaQuery = window.matchMedia(query);
/* window.matchMedia() match if the media query you passed
is match with current media query and return boolean value
*/
if (mediaQuery.matches !== matches) {
setMatches(mediaQuery.matches);
}
const listener = () => setMatches(mediaQuery.matches);
mediaQuery.addListener(listener);
return () => mediaQuery.removeListener(listener);
}, [query, matches]);
return matches; //=== return boolean value.
};
//=== Usage
import { useMediaQuery } from './useMediaQuery';
const App = () => {
const isSmallScreen = useMediaQuery('(max-width: 768px)');
return (
<div>
{isSmallScreen ? (
<h1>Mobile view</h1>
) : (
<h1>Desktop view</h1>
)}
</div>
);
};
export default App;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment