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; |
Hi I tried to use this on my project. I imported the function and console logged it. I got on the browser console some words, like Prototype, constructor, but no width nor height. How should I use this to get my width and height? thanks
This is a React Hook, so you need to import and use it inside a React component to the the windowSize variable.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi I tried to use this on my project. I imported the function and console logged it. I got on the browser console some words, like Prototype, constructor, but no width nor height. How should I use this to get my width and height? thanks