useWindowSize()

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

The Hook

1import { useState } from 'react'
2
3// See: https://usehooks-ts.com/react-hook/use-event-listener
4import { useEventListener } from '../useEventListener'
5// See: https://usehooks-ts.com/react-hook/use-isomorphic-layout-effect
6import { useIsomorphicLayoutEffect } from '../useIsomorphicLayoutEffect'
7
8interface WindowSize {
9 width: number
10 height: number
11}
12
13function useWindowSize(): WindowSize {
14 const [windowSize, setWindowSize] = useState<WindowSize>({
15 width: 0,
16 height: 0,
17 })
18
19 const handleSize = () => {
20 setWindowSize({
21 width: window.innerWidth,
22 height: window.innerHeight,
23 })
24 }
25
26 useEventListener('resize', handleSize)
27
28 // Set size at the first client-side load
29 useIsomorphicLayoutEffect(() => {
30 handleSize()
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 '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 »