Skip to content

Instantly share code, notes, and snippets.

@paulohfev
Created July 1, 2022 16:51
Show Gist options
  • Save paulohfev/c2927af9117285ccaa7af5524ea5cdd8 to your computer and use it in GitHub Desktop.
Save paulohfev/c2927af9117285ccaa7af5524ea5cdd8 to your computer and use it in GitHub Desktop.
Custom React hook for getting the current screen's dimensions
import { useState, useEffect } from 'react';
const getWindowDimensions = () => {
const { innerWidth: width, innerHeight: height } = window;
return { width, height };
}
const useWindowDimensions = () => {
const [windowDimensions, setWindowDimensions] = useState(getWindowDimensions());
useEffect(() => {
function handleResize() {
setWindowDimensions(getWindowDimensions());
}
window.addEventListener('resize', handleResize);
return () => window.removeEventListener('resize', handleResize);
}, []);
return windowDimensions;
}
export default useWindowDimensions;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment