Skip to content

Instantly share code, notes, and snippets.

@LeandrodeLimaC
Created December 9, 2022 14:49
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save LeandrodeLimaC/997f8608d56aa9f9402d23a790c329df to your computer and use it in GitHub Desktop.
Save LeandrodeLimaC/997f8608d56aa9f9402d23a790c329df to your computer and use it in GitHub Desktop.
React hook to check if user is on a Mobile devive
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