React useMediaQuery hook
Checks if the current environment matches a given media query and returns the appropriate value.
- Check if
Window
andWindow.matchMedia()
exist. ReturnwhenFalse
if not (e.g. SSR environment or unsupported browser). - Use
Window.matchMedia()
to match the givenquery
. Cast itsmatches
property to a boolean and store in a state variable,match
, using theuseState()
hook. - Use the
useEffect()
hook to add a listener for changes and to clean up the listeners after the hook is destroyed. - Return either
whenTrue
orwhenFalse
based on the value ofmatch
.
const useMediaQuery = (query, whenTrue, whenFalse) => {
if (typeof window === 'undefined' || typeof window.matchMedia === 'undefined')
return whenFalse;
const mediaQuery = window.matchMedia(query);
const [match, setMatch] = React.useState(!!mediaQuery.matches);
React.useEffect(() => {
const handler = () => setMatch(!!mediaQuery.matches);
mediaQuery.addListener(handler);
return () => mediaQuery.removeListener(handler);
}, []);
return match ? whenTrue : whenFalse;
};