Skip to content

Instantly share code, notes, and snippets.

@renanlido
Created October 28, 2021 19:35
Show Gist options
  • Save renanlido/e7533ba0601a8eaf5f8093795a11ce2c to your computer and use it in GitHub Desktop.
Save renanlido/e7533ba0601a8eaf5f8093795a11ce2c to your computer and use it in GitHub Desktop.
React hook to get window dimensions in real time
import { useEffect, useState } from 'react';
function getWindowDimensions() {
const { innerWidth: width, innerHeight: height } = window;
return {
width,
height
};
}
export default function useWindowDimensions() {
const [windowDimensions, setWindowDimensions] = useState(
getWindowDimensions()
);
useEffect(() => {
function handleResize() {
setWindowDimensions(getWindowDimensions());
}
window.addEventListener('resize', handleResize);
return () => window.removeEventListener('resize', handleResize);
}, []);
return windowDimensions;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment