Created
December 9, 2022 14:49
-
-
Save LeandrodeLimaC/997f8608d56aa9f9402d23a790c329df to your computer and use it in GitHub Desktop.
React hook to check if user is on a Mobile devive
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 { useEffect, useState, useRef } from 'react' | |
const MOBILE_BREAKPOINT = 640 | |
let defaultWindowWidth = 0 | |
/* | |
If using Nextjs, the following validation is necessary to ensure that we only try | |
to access the innerWidth when our code is running on user browser (client-side) | |
*/ | |
if (typeof window !== 'undefined') { | |
defaultWindowWidth = window.innerWidth | |
} | |
export const useUserDevice = () => { | |
const isMounted = useRef(false) | |
const [windowWidth, setWindowWidth] = useState(defaultWindowWidth) | |
const handleWindowResize = () => | |
isMounted && setWindowWidth(window.innerWidth) | |
useEffect(() => { | |
isMounted.current = true | |
setWindowWidth(window.innerWidth) | |
window.addEventListener('resize', handleWindowResize) | |
return () => { | |
isMounted.current = false | |
window.removeEventListener('resize', handleWindowResize) | |
} | |
}, []) | |
return { | |
isMobile: windowWidth <= MOBILE_BREAKPOINT, | |
width: windowWidth | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment