Created
December 5, 2022 02:50
-
-
Save santoshvijapure/67da2111677dbc65a3fce41b7a122bf8 to your computer and use it in GitHub Desktop.
React hook to determine the client device based on the screen size
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 { useLayoutEffect, useState } from 'react'; | |
import debounce from 'lodash/debounce'; | |
const useIsMobile = (): boolean => { | |
const [isMobile, setIsMobile] = useState(false); | |
useLayoutEffect(() => { | |
const updateSize = (): void => { | |
setIsMobile(window.innerWidth < 768); | |
}; | |
window.addEventListener('resize', debounce(updateSize, 250)); | |
// updateSize(); | |
return (): void => window.removeEventListener('resize', updateSize); | |
}, []); | |
return isMobile; | |
}; | |
export default useIsMobile; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment