useWindowSize
Returns reactive inner and outer browser window dimensions.
About
useWindowSize subscribes to window resize events and returns both viewport and outer browser-window dimensions.
Example
import { useWindowSize } from "rooks";
export default function WindowDimensions() {
const { innerWidth, innerHeight, outerWidth, outerHeight } = useWindowSize();
return (
<dl>
<dt>Viewport</dt>
<dd>
{innerWidth ?? "unknown"} × {innerHeight ?? "unknown"}
</dd>
<dt>Outer window</dt>
<dd>
{outerWidth ?? "unknown"} × {outerHeight ?? "unknown"}
</dd>
</dl>
);
}Parameters
This hook has no parameters.
Return value
It returns an object with innerHeight, innerWidth, outerHeight, and outerWidth. Every field is number | null; all four are null in the server snapshot.
Behavior and lifecycle
The hook uses React's external-store subscription contract and listens for window resize. It reads all four dimensions for each snapshot but preserves object identity when none changed. The listener is removed on unmount.
Compatibility and accessibility
Server rendering uses null dimensions, then React reads browser dimensions after hydration. Render a neutral fallback for null instead of guessing a device width. JavaScript viewport branching should not replace responsive CSS, and resizing must not hide focused or essential content.
Related
- useOnWindowResize runs a callback for resize events.
- useWindowScrollPosition returns scroll coordinates.
- SSR and browser APIs covers server snapshots.