DOM
useWindowSize
Tracks the viewport's { width, height }, updated on resize.
Demo
live · imported from hookli
- width
- —
- height
- —
- breakpoint
- —
Resize the window — both values update on every resize event, and the breakpoint label tracks Tailwind’s default ladder.
import { useWindowSize } from "hookli";
export function Demo() {
const { width, height } = useWindowSize();
return <p>{width} × {height}</p>;
}Usage
import { useWindowSize } from "hookli";
export function Demo() {
const { width, height } = useWindowSize();
return <p>{width} × {height}</p>;
}API
useWindowSize(options?: UseWindowSizeOptions): WindowSizeParameters
| Name | Type | Default | Description |
|---|---|---|---|
| options | UseWindowSizeOptions | {} | Hydration behaviour. Optional. |
Returns
| Name | Type | Description |
|---|---|---|
| width | number | The viewport's inner width in pixels. 0 on the server and until hydration. |
| height | number | The viewport's inner height in pixels. 0 on the server and until hydration. |
WindowSize
The viewport size reported by useWindowSize.
| Name | Type | Description |
|---|---|---|
| width | number | The viewport's inner width in pixels. |
| height | number | The viewport's inner height in pixels. |
UseWindowSizeOptions
Configures mount behaviour.
| Name | Type | Description |
|---|---|---|
| initializeWithValue | boolean | Read the real size synchronously on mount. Set false to start at 0 and populate after hydration. |
Hook
The implementation, straight from hookli. Copy it, or install the package.
import { useState } from "react";
import { useEventListener } from "../use-event-listener/use-event-listener";
import { useIsomorphicLayoutEffect } from "../use-isomorphic-layout-effect/use-isomorphic-layout-effect";
interface WindowSize {
width: number;
height: number;
}
interface UseWindowSizeOptions {
initializeWithValue?: boolean;
}
const IS_SERVER = typeof window === "undefined";
export function useWindowSize(options: UseWindowSizeOptions = {}): WindowSize {
const { initializeWithValue = true } = options;
const readSize = (): WindowSize => ({
width: window.innerWidth,
height: window.innerHeight,
});
const [windowSize, setWindowSize] = useState<WindowSize>(() => {
if (initializeWithValue && !IS_SERVER) return readSize();
return { width: 0, height: 0 };
});
const handleSize = () => {
if (IS_SERVER) return;
setWindowSize(readSize());
};
useEventListener("resize", handleSize);
useIsomorphicLayoutEffect(() => {
handleSize();
}, []);
return windowSize;
}