Skip to content
Branch: master
Find file Copy path
Find file Copy path
@antonioru antonioru useDrag ac5a719 Jan 14, 2020
2 contributors

Users who have contributed to this file

@antonioru @avitorio
42 lines (28 sloc) 1.15 KB


Accepts a media query string then uses the matchMedia API to determine if it matches with the current document.

It also monitor the document changes to detect when it stops matching the given media query.

Returns the validity state of the given media query.

Why? πŸ’‘

  • takes care of re-rendering the component when the given media query changes
  • get rid of the listener when the component will unmount
import { useMediaQuery } from 'beautiful-react-hooks'; 

const MediaQueryReporter = () => {
  const isSmall = useMediaQuery('(max-width: 48rem)'); 
  const isLarge = useMediaQuery('(min-width: 48rem)'); 
  return (
     <p>Small view? {isSmall ? 'yes' : 'no'}</p>
     <p>Large view? {isLarge ? 'yes' : 'no'}</p>

<MediaQueryReporter />

Mastering the hook

βœ… When to use

  • When a component should have a different layout/behaviour on different medias
  • Mount/Unmount sub-components according to a defined media-query

πŸ›‘ When not to use

  • Do not use this hook to define the user device
You can’t perform that action at this time.