UNPKG

701 BJavaScriptView Raw
1import { useEffect, useState } from 'react'
2
3export default function useWindowSize() {
4 const isClient = typeof window === 'object',
5 [windowSize, setWindowSize] = useState(getSize)
6
7 function getSize() {
8 return {
9 width: isClient ? window.innerWidth : undefined,
10 height: isClient ? window.innerHeight : undefined,
11 }
12 }
13
14 useEffect(() => {
15 if (!isClient) {
16 return false
17 }
18
19 function handleResize() {
20 setWindowSize(getSize())
21 }
22
23 window.addEventListener('resize', handleResize)
24 return () => window.removeEventListener('resize', handleResize)
25 }, []) // Empty array ensures that effect is only run on mount and unmount
26
27 return windowSize
28}