-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//=== 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