Skip to content

Instantly share code, notes, and snippets.

@JayMGurav
Last active July 7, 2021 12:33
Show Gist options
  • Save JayMGurav/d82ed6dd5a263b1fa1ecef1aa638e485 to your computer and use it in GitHub Desktop.
Save JayMGurav/d82ed6dd5a263b1fa1ecef1aa638e485 to your computer and use it in GitHub Desktop.
useViewportSize hook to get the view port size
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