useWindowSize
useWindowSize is a custom hook to track the size of the browser window in real-time.
Usage
import { useWindowSize } from "hookify-react";
export default function UseWindowSizeExample() {
const { width, height } = useWindowSize();
return (
<div style={{ padding: "20px", border: "1px solid black" }}>
<p>Window Width: {width}px</p>
<p>Window Height: {height}px</p>
</div>
);
}
API Reference
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
| None | - | - | This hook does not take any parameters. It tracks the size of the browser window. |
Return Value
| Property | Type | Description |
|---|---|---|
width | number | The current width of the browser window. |
height | number | The current height of the browser window. |
Behavior
- Tracks browser window dimensions (
width,height) in real time. - Listens for the
resizeevent and updates state viauseLayoutEffect. - Removes the
resizelistener on unmount.
SSR Safety
- Safe to use during server-side rendering: when
windowis undefined it returns{ width: 0, height: 0 }. - After hydration it corrects the values to the real window size using
useLayoutEffect, avoiding a visible flicker.