useWindowSize()

Easily retrieve window dimensions with this React Hook which also works onResize.

The Hook

1import { useState } from 'react'
2
3import { useEventListener, useIsomorphicLayoutEffect } from 'usehooks-ts'
4
5interface WindowSize {
6 width: number
7 height: number
8}
9
10function useWindowSize(): WindowSize {
11 const [windowSize, setWindowSize] = useState<WindowSize>({
12 width: 0,
13 height: 0,
14 })
15
16 const handleSize = () => {
17 setWindowSize({
18 width: window.innerWidth,
19 height: window.innerHeight,
20 })
21 }
22
23 useEventListener('resize', handleSize)
24
25 // Set size at the first client-side load
26 useIsomorphicLayoutEffect(() => {
27 handleSize()
28 // eslint-disable-next-line react-hooks/exhaustive-deps
29 }, [])
30
31 return windowSize
32}
33
34export default useWindowSize

Usage

1import { useWindowSize } from 'usehooks-ts'
2
3export default function Component() {
4 const { width, height } = useWindowSize()
5
6 return (
7 <div>
8 The current window dimensions are:{' '}
9 <code>{JSON.stringify({ width, height })}</code>
10 </div>
11 )
12}

Edit on CodeSandbox

See a way to make this page better?
Edit there »