Skip to content

Instantly share code, notes, and snippets.

@joshcawthorne
Last active October 5, 2023 13:21
Show Gist options
  • Save joshcawthorne/0a518b164658510f4eed74d0c4e8d003 to your computer and use it in GitHub Desktop.
Save joshcawthorne/0a518b164658510f4eed74d0c4e8d003 to your computer and use it in GitHub Desktop.
SSR-Compatible (NextJS, Gatsby etc) React hook for getting Window Size.
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;
@MrFacundo
Copy link

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

@alexmasny
Copy link

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