# useWindowSize

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

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

## Usage

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

## 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

```ts
function useWindowSize(serverValue?: WindowSize): WindowSize
```

| Parameter | Description |
| --- | --- |
| `serverValue` | Size on the server and during hydration. Default `{ width: 0, height: 0 }`. Pass a constant, not an inline object. |

### Types

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

## Browser support

Works in all modern browsers.

---

168 B minified and brotlied
Source: https://github.com/vincentri/react-tils/blob/main/src/useWindowSize.ts
Docs page: https://vincentri.github.io/react-tils/hooks/useWindowSize/
Previous: [useMediaQuery](https://vincentri.github.io/react-tils/hooks/useMediaQuery.md)
Next: [useVisualViewport](https://vincentri.github.io/react-tils/hooks/useVisualViewport.md)
