Created
February 21, 2021 20:24
-
-
Save sujinleeme/33b8f0f4c8569dc182b8715b345a4ec4 to your computer and use it in GitHub Desktop.
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 { useState, useEffect } from "react"; | |
interface Dimensions { | |
width: number | null; | |
height: number | null; | |
} | |
export const useWindowDimensions = (): Dimensions => { | |
const hasWindow = typeof window !== "undefined"; | |
const getWindowDimensions = (): Dimensions => { | |
const width = hasWindow ? window.innerWidth : null; | |
const height = hasWindow ? window.innerHeight : null; | |
return { | |
width, | |
height, | |
}; | |
}; | |
const [windowDimensions, setWindowDimensions] = useState<Dimensions>( | |
getWindowDimensions() | |
); | |
useEffect(() => { | |
if (hasWindow) { | |
const handleResize = () => setWindowDimensions(getWindowDimensions()); | |
window.addEventListener("resize", handleResize); | |
return () => window.removeEventListener("resize", handleResize); | |
} | |
}, [hasWindow]); | |
return windowDimensions; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment