useWindowSize()

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

The Hook

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

Usage

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

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