19

🍉useMediaQuery improves your code readability and allows you to have different l...

 4 years ago
source link: https://github.com/beautifulinteractions/beautiful-react-hooks/blob/master/docs/useMediaQuery.md
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

useMediaQuery

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? :bulb:

  • 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 (
   <DisplayDemo>
     <p>Small view? {isSmall ? 'yes' : 'no'}</p>
     <p>Large view? {isLarge ? 'yes' : 'no'}</p>
   </DisplayDemo>
  );
};

<MediaQueryReporter />

Mastering the hook

:white_check_mark: 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

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK