Created
May 13, 2020 01:42
-
-
Save KirdesMF/0004373f4c54eb6eff39e6f7815b7820 to your computer and use it in GitHub Desktop.
useMatchMeadi Hooks
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useState, useEffect } from 'react'; | |
const useMatchMedia = (mediaQuery: string) => { | |
const [isMatches, setIsMatches] = useState( | |
window.matchMedia(mediaQuery).matches | |
); | |
useEffect(() => { | |
const updateStateisMatches = (event: MediaQueryListEvent) => | |
setIsMatches(event.matches); | |
const mediaQueryList = window.matchMedia(mediaQuery); | |
setIsMatches(mediaQueryList.matches); | |
mediaQueryList.addListener(updateStateisMatches); | |
return () => mediaQueryList.removeListener(updateStateisMatches); | |
}, [mediaQuery]); | |
return isMatches; | |
}; | |
export { useMatchMedia }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment