Last active
October 15, 2019 04:47
-
-
Save udittyagi/35926d157408b4e0ca6114dd6c457f2e to your computer and use it in GitHub Desktop.
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
const useBreakpoint = (queries) => { | |
const [queryMatch, setQueryMatch] = useState(null); | |
useEffect(() => { | |
const mediaQueryLists = {}; | |
const keys = Object.keys(queries); | |
// To check whether event listener is attached or not | |
let isAttached = false; | |
const handleQueryListener = () => { | |
const updatedMatches = keys.reduce((acc, media) => { | |
acc[media] = !!(mediaQueryLists[media] && mediaQueryLists[media].matches); | |
return acc; | |
}, {}) | |
//Setting state to the updated matches | |
// when document either starts or stops matching a query | |
setQueryMatch(updatedMatches) | |
} | |
if (window && window.matchMedia) { | |
const matches = {}; | |
keys.forEach(media => { | |
if (typeof queries[media] === 'string') { | |
mediaQueryLists[media] = window.matchMedia(queries[media]); | |
matches[media] = mediaQueryLists[media].matches | |
} else { | |
matches[media] = false | |
} | |
}); | |
//Setting state to initial matching queries | |
setQueryMatch(matches); | |
isAttached = true; | |
keys.forEach(media => { | |
if(typeof queries[media] === 'string') { | |
mediaQueryLists[media].addListener(handleQueryListener); | |
} | |
}); | |
} | |
return () => { | |
//If event listener is attached then remove it when deps change | |
if(isAttached) { | |
keys.forEach(media => { | |
if(typeof queries[media] === 'string') { | |
mediaQueryLists[media].removeListener(handleQueryListener); | |
} | |
}); | |
} | |
} | |
}, [queries]); | |
return queryMatch; | |
} | |
export default useBreakpoint; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment