A minimalistic, modern React hook for listening to window resize events with built-in debouncing.
- Minimalistic: Tiny footprint, no external dependencies.
- Modern: Written in TypeScript, built as a React Hook.
- Performant: Built-in debouncing and passive event listeners to prevent excessive re-renders and scroll jank.
- SSR Safe: Checks for
windowexistence, safe to use in Next.js/Gatsby/Remix.
npm install react-window-size-listener
# or
yarn add react-window-size-listener
# or
pnpm add react-window-size-listenerThis hook returns an object containing the current width and height of the window.
import React from 'react';
import { useWindowSize } from 'react-window-size-listener';
function App() {
const { width, height } = useWindowSize();
return (
<div>
<h1>Window Size</h1>
<p>Width: {width}px</p>
<p>Height: {height}px</p>
</div>
);
}When using with Next.js App Router, ensure you use the "use client" directive since this hook relies on browser APIs.
"use client";
import { useWindowSize } from 'react-window-size-listener';
export default function ClientComponent() {
const { width } = useWindowSize();
return <div>Window width: {width}</div>;
}You can easily compose this hook to create a breakpoint helper.
import { useWindowSize } from 'react-window-size-listener';
const useBreakpoint = () => {
const { width } = useWindowSize();
if (width < 640) return 'sm';
if (width < 768) return 'md';
if (width < 1024) return 'lg';
return 'xl';
};You can customize the debounce time by passing an options object. The default is 100ms.
// Wait 500ms after the last resize event before updating state
const { width, height } = useWindowSize({ debounceTime: 500 });Returns the visual viewport size using the Visual Viewport API. This accounts for pinch-zoom, on-screen keyboards, and browser chrome on mobile devices. Falls back to window dimensions if the API is not available.
import { useViewportSize } from 'react-window-size-listener';
function App() {
const { width, height } = useViewportSize();
return (
<div>
<p>Viewport: {width} x {height}</p>
</div>
);
}Tracks window.innerWidth and window.innerHeight.
Tracks the visual viewport dimensions (with fallback to window dimensions).
| Property | Type | Default | Description |
|---|---|---|---|
options.debounceTime |
number |
100 |
Delay in ms before updating state after resize |
| Returns | WindowSize |
Object { width: number, height: number } |
The library exports the following types for your convenience:
import type { WindowSize, UseWindowSizeOptions } from 'react-window-size-listener';Version 2.0.0 is a complete rewrite. The old Class Component WindowSizeListener and HOC withWindowSizeListener have been removed in favor of the useWindowSize hook.
Old way (v1):
<WindowSizeListener onResize={windowSize => console.log(windowSize)} />New way (v2.0+):
const { width, height } = useWindowSize();
useEffect(() => {
console.log({ width, height });
}, [width, height]);MIT