Last active
February 24, 2025 06:43
-
-
Save joshcawthorne/0a518b164658510f4eed74d0c4e8d003 to your computer and use it in GitHub Desktop.
SSR-Compatible (NextJS, Gatsby etc) React hook for getting Window Size.
This file contains hidden or 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"; | |
function useWindowSize() { | |
const [windowSize, setWindowSize] = useState<{ width: number | undefined; height: number | undefined }>({ | |
width: undefined, | |
height: undefined, | |
}); | |
useEffect(() => { | |
function 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
This is a React Hook, so you need to import and use it inside a React component to the the windowSize variable.