Dan Stroot

useMediaQuery

useMediaQuery is a react hook that makes testing for media query matches in your code easier and simpler.

Date:


Code

useMediaQuery.js
(javascript)
import { useEffect, useState } from 'react'
 
export const useMediaQuery = (query) => {
  const [state, setState] = useState(false)
 
  useEffect(() => {
    let mounted = true
 
    // Returns a MediaQueryList object
    const mql = window.matchMedia(query)
    const onChange = () => {
      if (!mounted) return
      setState(!!mql.matches)
    }
 
    mql.addListener(onChange)
    setState(mql.matches)
 
    // clean up
    return () => {
      mounted = false
      mql.removeListener(onChange)
    }
  }, [query])
 
  return state
}

Context

If you have a special case, when you need to get media query result inside you react app (for example, you want to show different components on mobile and desktop) this is the way to do so.

Usage

useMediaQueryExample.jsx
(javascript)
const EffecfulComponent = () => {
  const result = useMediaQuery(`screen and (max-width: 400px)`);
  return <span>{result.toString()}</span>;
};
 
const biggerThan400 = useMediaQuery(`(min-width: 400px)`);
 
return <div>
    {biggerThan400 && <button>SomeButton</button>}
</div>

Sharing is Caring

Edit this page