Created
February 27, 2019 09:55
-
-
Save jefflau/ae10c61495371aa3fe54cd97a3969209 to your computer and use it in GitHub Desktop.
useMedia hook
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 useMedia = (query, defaultState) => { | |
const [state, setState] = useState(defaultState) | |
useEffect( | |
() => { | |
let mounted = true | |
const mql = window.matchMedia(query) | |
const onChange = () => { | |
if (!mounted) return | |
setState(!!mql.matches) | |
} | |
mql.addListener(onChange) | |
setState(mql.matches) | |
return () => { | |
mounted = false | |
mql.removeListener(onChange) | |
} | |
}, | |
[query] | |
) | |
return state | |
} | |
export const useMediaMin = (bp, defaultState) => | |
useMedia(`(min-width: ${breakpoints[bp]}px)`, defaultState) | |
export const useMediaMax = (bp, defaultState) => | |
useMedia(`(max-width: ${breakpoints[bp] - 1}px)`, defaultState) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment