Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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