Created
October 28, 2021 19:35
-
-
Save renanlido/e7533ba0601a8eaf5f8093795a11ce2c to your computer and use it in GitHub Desktop.
React hook to get window dimensions in real time
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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