useWindowSize
Browser & deviceA React hook for tracking the browser window size with debounce/throttle and SSR support
Install
$ npm install @usefy/use-window-sizeQuick start
useWindowSize.tsx
import { useWindowSize } from "@usefy/use-window-size";
function MyComponent() {
const { width, height } = useWindowSize();
return (
<div>
{width} × {height}
{width < 768 ? <MobileView /> : <DesktopView />}
</div>
);
}API reference
useWindowSize(options?)
A hook that tracks the browser window size and returns { width, height }.
Parameters
| Parameter | Type | Description |
|---|---|---|
options | UseWindowSizeOptions | Optional configuration object |
Options
| Option | Type | Default | Description |
|---|---|---|---|
initialWidth | number | 0 | Width returned before the window can be measured (SSR / first server render) |
initialHeight | number | 0 | Height returned before the window can be measured (SSR / first server render) |
debounceMs | number | 0 | Debounce resize updates by this many ms. Takes precedence over throttleMs |
throttleMs | number | 0 | Throttle resize updates to at most once per this many ms. Ignored when debounceMs is set |
includeScrollbar | boolean | true | true uses innerWidth/innerHeight (includes scrollbar); false uses documentElement client sizes |
enabled | boolean | true | When false, no resize listener is attached and the last known size is kept |
onChange | (size: WindowSize) => void | — | Callback fired whenever the window size changes |
Returns WindowSize
| Property | Type | Description |
|---|---|---|
width | number | Current window width in pixels |
height | number | Current window height in pixels |
Exported Helpers
| Helper | Description |
|---|---|
isWindowAvailable() | Returns true in a browser environment, false in SSR |
getWindowSize(includeScrollbar?) | Reads the current window size (returns { width: 0, height: 0 } in SSR) |
areSizesEqual(a, b) | Compares two WindowSize values for equality |
Go deeper
This page is the quick reference. For every example, prop, and edge case, read the full README — or open Storybook to change props live.