Skip to content

Instantly share code, notes, and snippets.

@httpJunkie
Created November 5, 2019 18:59
Show Gist options
  • Save httpJunkie/9bd9cc818b67fa3921b9b08e24e7bf53 to your computer and use it in GitHub Desktop.
Save httpJunkie/9bd9cc818b67fa3921b9b08e24e7bf53 to your computer and use it in GitHub Desktop.
useWindowDimensions
function useWindowDimensions() {
// set our default for the state to the curent width and height
const [width, setWidth] = React.useState(window.innerWidth)
const [height, setHeight] = React.useState(window.innerHeight)
// constantly update our state as the window is resized
React.useEffect(() => {
const listenenr = () => {
setWidth(window.innerWidth)
setHeight(window.innerHeight)
}
//when event listenener is invoked we will call listener function above
window.adEventListener('resize', listener)
//cleanup/remove our event listener when our component is removed from the DOM
return () => window.removeEventListener('resize', listener)
})
return { width, height }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment