Last active
July 10, 2020 02:23
-
-
Save adbutterfield/bcb2ffae73bb6b8430de25aaca97d354 to your computer and use it in GitHub Desktop.
React hook for responsive fun
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 { useState, useLayoutEffect } from 'react'; | |
const useOnMobile = () => { | |
const [isMobile, setIsMobile] = useState(true); | |
const resizeCallback = () => { | |
if (window.innerWidth < 768) { | |
setIsMobile(true); | |
} else { | |
setIsMobile(false); | |
} | |
}; | |
useLayoutEffect(() => { | |
if (window.innerWidth > 767) { | |
setIsMobile(false); | |
} | |
window.addEventListener('resize', resizeCallback); | |
return () => { | |
window.removeEventListener('resize', resizeCallback); | |
}; | |
}, []); | |
return isMobile; | |
}; | |
export default useOnMobile; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment