Skip to content

Instantly share code, notes, and snippets.

@Rem0ld
Created January 14, 2021 10:57
Show Gist options
  • Save Rem0ld/7972eb01e73bae6ae7738b3e2982897d to your computer and use it in GitHub Desktop.
Save Rem0ld/7972eb01e73bae6ae7738b3e2982897d to your computer and use it in GitHub Desktop.
React hook to get the dimensions of the window
import { useState, useEffect } from "react";
function getWindowDimensions() {
const { innerWidth: width, innerHeight: height } = window;
return {
width,
height,
};
}
export default function useWindowDimension() {
const [windowDimensions, setWindowDimensions] = useState(
getWindowDimensions()
);
useEffect(() => {
function handleResize() {
setWindowDimensions(getWindowDimensions());
}
window.addEventListener("resize", handleResize);
return () => window.removeEventListener("resize", handleResize);
}, []);
return windowDimensions;
}
// Found at: https://stackoverflow.com/questions/36862334/get-viewport-window-height-in-reactjs
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment