useWindowSize

React hook to measure window or element dimensions with responsive resize listeners and reactive callbacks.

pnpm add react-callback-hooks

Demo

Window SizeResize browser window
Width0px
Height0px
Element Size (via Ref)Drag corner to resize
0px × 0pxResizable container

Usage

Window dimensions:

import { useWindowSize } from 'react-callback-hooks'

const [size] = useWindowSize((size) => {
  console.log('Window resized to', size.width, size.height)
})

Element dimensions via ref:

const [size, ref] = useWindowSize<HTMLDivElement>((size) => {
  console.log('Element resized to', size.width, size.height)
})

<div ref={ref} />

Object form:

const [size, ref] = useWindowSize<HTMLDivElement>({
  onChange: (size) => console.log('Changed', size),
  onResize: (size) => console.log('Resized', size),
})

Parameters

Simple form

ParameterTypeDescription
callback(size: WindowSize) => voidOptional. Called whenever the window or referenced element is resized.

Object form

PropertyTypeDescription
onChange(size: WindowSize) => voidCalled whenever the window or referenced element is resized.
onResize(size: WindowSize) => voidAlias for onChange.

Return Values

Returns a tuple [size, ref]:

TypeDescription
size.widthnumberCurrent width in pixels.
size.heightnumberCurrent height in pixels.
refReact.RefObject<T>Optional ref to measure and observe a specific element instead of the window.