Created
April 15, 2020 14:16
-
-
Save TonyDotDev/4ae15e80aa559f7f1b0d99b55457af38 to your computer and use it in GitHub Desktop.
React hook to get window 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 { useState, useEffect } from "react"; | |
export const useWindowSize = () => { | |
const isClient = typeof window === "object"; | |
const getSize = () => { | |
return { | |
width: isClient ? window.innerWidth : undefined, | |
height: isClient ? window.innerHeight : undefined, | |
}; | |
}; | |
const [windowSize, setWindowSize] = useState(getSize); | |
useEffect(() => { | |
if (!isClient) { | |
return false; | |
} | |
const handleResize = () => { | |
setWindowSize(getSize()); | |
}; | |
window.addEventListener("resize", handleResize); | |
return () => window.removeEventListener("resize", handleResize); | |
}, []); | |
return windowSize; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment