Last active
July 7, 2021 12:33
-
-
Save JayMGurav/d82ed6dd5a263b1fa1ecef1aa638e485 to your computer and use it in GitHub Desktop.
useViewportSize hook to get the view port size
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 } from 'react'; | |
import debounce from 'lodash.debounce'; | |
interface ViewportSize { | |
width: number; | |
height: number; | |
} | |
function useViewportSize() { | |
const [viewportSize, setViewportSize] = useState<ViewportSize>({ | |
width: 0, | |
height: 0, | |
}); | |
useEffect(() => { | |
const viewportSizeSetter = () => { | |
setViewportSize({ | |
width: window.visualViewport?.width ?? window.innerWidth, | |
height: window.visualViewport?.height ?? window.innerHeight, | |
}); | |
}; | |
viewportSizeSetter(); | |
const debounced = debounce(viewportSizeSetter, 1000); | |
window.addEventListener('resize', debounced); | |
return () => { | |
debounced.cancel(); | |
window.removeEventListener('resize', debounced); | |
}; | |
}, []); | |
return viewportSize; | |
} | |
export default useViewportSize; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment