Skip to content

Instantly share code, notes, and snippets.

@max10rogerio
Created March 26, 2020 15:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save max10rogerio/c4aeaec62178ac56e17454c04e797e44 to your computer and use it in GitHub Desktop.
Save max10rogerio/c4aeaec62178ac56e17454c04e797e44 to your computer and use it in GitHub Desktop.
Hook to verify size screen by param
import { useEffect, useState } from 'react';
/**
* Exemple of sizes:
* mobile: '(min-width: 425px)'
* tablet: '(min-width: 768px)'
* laptop: '(min-width: 1024px)'
* @param {String} size
* @returns {boolean}
*/
export const useMedia = (size) => {
const mediaSize = window.matchMedia(size);
const getValue = () => {
return !mediaSize.matches;
};
const [match, setMatch] = useState(getValue);
useEffect(() => {
const handler = () => setMatch(getValue);
mediaSize.addListener(handler);
return () => mediaSize.removeListener(handler);
}, []);
return match;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment