Skip to content

Instantly share code, notes, and snippets.

@alexcloudstar
Created September 9, 2021 17:39
Show Gist options
  • Save alexcloudstar/2d41a077519b353bdc7f4f7ebaca669f to your computer and use it in GitHub Desktop.
Save alexcloudstar/2d41a077519b353bdc7f4f7ebaca669f to your computer and use it in GitHub Desktop.
import { useState, useEffect } from 'react';
const useWindowSize = () => {
const [windowSize, setWindowSize] = useState<{
width: number | undefined;
height: number | undefined;
}>({
width: undefined,
height: undefined
});
useEffect(() => {
if (typeof window !== 'undefined') {
const handleResize = () => {
setWindowSize({
width: window.innerWidth,
height: window.innerHeight
});
};
window.addEventListener('resize', handleResize);
handleResize();
return () => window.removeEventListener('resize', handleResize);
}
}, []);
return windowSize;
};
export default useWindowSize;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment