useWindowSize
A React hook that provides the current window size (width and height) and automatically updates when the window is resized.
- Installation
- Add Source Code
npm install @plenty-hooks/use-window-size
npx @plenty-hooks/cli use-window-size
Using this command will add the source code of the hook directly to your project.
Options:
--pathor-p: Specify the directory where the hook file should be saved--kebab-caseor-k: Use kebab-case for the output filename (e.g.,use-document-title.ts). By default, the filename uses camelCase (e.g.,useDocumentTitle.ts)
Note: By adding the source code of the hook directly to your project, you won't be able to install further updates automatically. You are on your own for maintaining and updating the code.
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 pixelsheight: number- The current window inner height in pixels
Server-Side Rendering (SSR)
During server-side rendering the hook returns { width: 0, height: 0 }.