Skip to content

Instantly share code, notes, and snippets.

@gh640
Created March 15, 2021 11:34
Show Gist options
  • Select an option

  • Save gh640/131e7017e2bdd2c918d312e87aa23f71 to your computer and use it in GitHub Desktop.

Select an option

Save gh640/131e7017e2bdd2c918d312e87aa23f71 to your computer and use it in GitHub Desktop.
React hook to get the reactive window size
import { useState, useEffect } from 'react'
function useWindowSize() {
const [windowSize, setWindowSize] = useState({
width: null,
height: null,
})
useEffect(() => {
const updateSize = () => {
setWindowSize({
width: window.innerWidth,
height: window.innerHeight,
})
}
window.addEventListener("resize", updateSize)
updateSize()
return () => window.removeEventListener("resize", updateSize)
}, [])
return windowSize
}
export default useWindowSize
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment