All hooks / Viewport and media

useWindowSize

168 B minified and brotliedSourceMarkdown✓ Works in all modern browsers

The window's inner width and height in CSS pixels, updated on resize. Like window.innerWidth, the width includes a visible vertical scrollbar; for the width without it, read document.documentElement.clientWidth or use useElementSize on a full-width element.

Renders serverValue on the server and during hydration, then switches to the real size with no hydration mismatch. Re-renders only when the size actually changes, on every resize event that changes it (not throttled).

Import

import { useWindowSize } from '@vincent.ri/react-tils'
// or only this hook
import { useWindowSize } from '@vincent.ri/react-tils/useWindowSize'

Usage

const { width, height } = useWindowSize()
return <canvas width={width} height={height} />

Live demo

Resize the window.

0×0

When to use it

JS needs exact pixel values, e.g. canvas sizing, virtualized lists, or positioning a popover inside the viewport.

When not to

You only need a breakpoint; use useMediaQuery, which re-renders only when the breakpoint flips. For styling, use CSS. For an element's size, use CSS container queries or useElementSize.

API

function useWindowSize(serverValue?: WindowSize): WindowSize
ParameterDescription
serverValueSize on the server and during hydration. Default { width: 0, height: 0 }. Pass a constant, not an inline object.

Types

export type WindowSize = {
  width: number;
  height: number;
};

Browser support

Uses only long-established browser features, so it works wherever React does.

First version with support, from MDN's compatibility data (web-features 3.42.0, @mdn/browser-compat-data 8.1.5).