you can just make your own custom hook like this working snippet of code
hooks/useStyleMediaQuery.js
import { useState, useEffect } from 'react'
export const useStyleMediaQuery = ({ mixOrMax, widthOrHeight, value }) => {
if (!mixOrMax) mixOrMax = 'min';
if (!widthOrHeight) widthOrHeight = 'width';
const [matches, setMatches] = useState(
window.matchMedia(`(${mixOrMax}-${widthOrHeight}: ${value}px)`).matches
)
useEffect(() => {
window
.matchMedia(`(${mixOrMax}-${widthOrHeight}: ${value}px)`)
.addEventListener('change', e => setMatches(e.matches));
}, [mixOrMax, widthOrHeight, value]);
return { matches }
}
App.js
import { useStyleMediaQuery } from 'hooks/useStyleMediaQuery'
import ComponentIwantToShowOnlyOnMobile from 'components/ComponentIwantToShowOnlyOnMobile'
import ComponentIwantToShowOnlyOnDesktop from 'components/ComponentIwantToShowOnlyOnDesktop'
function App() {
const { matches: isMobile } = useStyleMediaQuery({ mixOrMax: 'max', widthOrHeight: 'width', value: 767 });
const { matches: imSmall } = useStyleMediaQuery({ mixOrMax: 'max', widthOrHeight: 'width', value: 400 });
return (
<>
{isMobile && <ComponentIwantToShowOnlyOnMobile />}
{!isMobile && <ComponentIwantToShowOnlyOnDesktop />}
{imSmall && <h1>I'm very small.. 400px width or less</h1>}
</>
);
}
export default App;
that's it :)