Skip to content

Instantly share code, notes, and snippets.

@sujinleeme
Created February 21, 2021 20:24
Show Gist options
  • Save sujinleeme/33b8f0f4c8569dc182b8715b345a4ec4 to your computer and use it in GitHub Desktop.
Save sujinleeme/33b8f0f4c8569dc182b8715b345a4ec4 to your computer and use it in GitHub Desktop.
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