useWindowSize.js
:
import {useState, useEffect} from 'react';
const REFRESH_TIMEOUT = 150;
const useWindowSize = () => {
const getSize = () => ({
width: window.innerWidth
|| document.documentElement.clientWidth
|| document.body.clientWidth,
height: window.innerHeight
|| document.documentElement.clientHeight
|| document.body.clientHeight
})
const [windowSize, setWindowSize] = useState(getSize)
useEffect(() => {
let timeoutId = null
const handleResize = () => {
clearTimeout(timeoutId)
timeoutId = setTimeout(() => setWindowSize(getSize), REFRESH_TIMEOUT)
}
window.addEventListener("resize", handleResize)
return () => window.removeEventListener("resize", handleResize)
}, [])
return windowSize
}
export default useWindowSize
Any component:
import React from "react"
import useWindowSize from "<path>/useWindowSize"
const Component = () => {
let windowSize = useWindowSize()
return (
//...
)
}
export default Component