Skip to content

Instantly share code, notes, and snippets.

@sturmenta
Created March 10, 2024 22:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sturmenta/bb80b1a03fc5620038c0bd37fbe49d4e to your computer and use it in GitHub Desktop.
Save sturmenta/bb80b1a03fc5620038c0bd37fbe49d4e to your computer and use it in GitHub Desktop.
window addEventListener resize
import { useEffect, useState } from "react"
export const useWindowSize = () => {
const [size, setSize] = useState({ vh: 0, vw: 0 })
const onResize = (props: any) =>
setSize({
vh: props.target.innerHeight,
vw: props.target.innerWidth
})
useEffect(() => {
if (window) {
setSize({ vh: window.innerHeight, vw: window.innerWidth }) // initial value
window.addEventListener("resize", onResize)
return () => {
window.removeEventListener("resize", onResize)
}
}
}, [])
return size
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment