useWindowSize()

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

The Hook

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

Usage

1import React from 'react'
2
3import { useWindowSize } from 'usehooks-ts'
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}

Edit on CodeSandbox

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