Skip to content

Instantly share code, notes, and snippets.

@eriksachse
Created September 24, 2021 15:35
Show Gist options
  • Save eriksachse/b596d6be54007f04bc2c8fee792a8fde to your computer and use it in GitHub Desktop.
Save eriksachse/b596d6be54007f04bc2c8fee792a8fde to your computer and use it in GitHub Desktop.
get window size hook
import { useState, useEffect } from "react";
export default function useWindowDimensions() {
const hasWindow = typeof window !== "undefined";
function getWindowDimensions() {
const width = hasWindow ? window.innerWidth : null;
const height = hasWindow ? window.innerHeight : null;
return {
width,
height,
};
}
const [windowDimensions, setWindowDimensions] = useState(
getWindowDimensions()
);
useEffect(() => {
if (hasWindow) {
function handleResize() {
setWindowDimensions(getWindowDimensions());
}
window.addEventListener("resize", handleResize);
return () => window.removeEventListener("resize", handleResize);
}
}, [hasWindow]);
return windowDimensions;
}
@eriksachse
Copy link
Author

usage:

import useWindowDimensions from "./hooks/useWindowDimensions";

export default function Masonry(props) {
  const { width, height } = useWindowDimensions();
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment