Created
October 11, 2019 09:56
-
-
Save freddi301/6b210f6a077b58f30cd5579bfc2c9cbe to your computer and use it in GitHub Desktop.
useMediaQuery #react #hook
This file contains hidden or 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 React from "react"; | |
/** | |
* Matches mediaquery, rerenders only when match changes | |
* @param query media query | |
*/ | |
export function useMediaQuery( | |
query: string | null | false, | |
defValue: boolean = false, | |
) { | |
const [matches, setMatches] = React.useState(() => | |
query ? window.matchMedia(query).matches : defValue, | |
); | |
React.useEffect(() => { | |
if (!query) { | |
return undefined; | |
} | |
let ignore = false; | |
const mql = window.matchMedia(query); | |
function onChange() { | |
if (!ignore) { | |
setMatches(mql.matches); | |
} | |
} | |
mql.addListener(onChange); | |
setMatches(mql.matches); | |
return () => { | |
ignore = true; | |
mql.removeListener(onChange); | |
}; | |
}, [query]); | |
return matches; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment