Skip to main content

useWindowSize

A React hook that provides the current window size (width and height) and automatically updates when the window is resized.

npm install @plenty-hooks/use-window-size

Showcase

import useWindowSize from '@plenty-hooks/use-window-size';

function ResponsiveComponent() {
const { width, height } = useWindowSize();

return (
<div>
<p>Window width: {width}px</p>
<p>Window height: {height}px</p>

{width < 768 && <div>Mobile view</div>}
{width >= 768 && width < 1024 && <div>Tablet view</div>}
{width >= 1024 && <div>Desktop view</div>}
</div>
);
}

API

useWindowSize()

Returns the current window size and automatically subscribes to window resize events.

Returns

An object containing:

  • width: number - The current window inner width in pixels
  • height: number - The current window inner height in pixels

Server-Side Rendering (SSR)

During server-side rendering the hook returns { width: 0, height: 0 }.