Skip to main content

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

ParameterTypeDefaultDescription
None--This hook does not take any parameters. It tracks the size of the browser window.

Return Value

PropertyTypeDescription
widthnumberThe current width of the browser window.
heightnumberThe current height of the browser window.

Behavior

  • Tracks browser window dimensions (width, height) in real time.
  • Listens for the resize event and updates state via useLayoutEffect.
  • Removes the resize listener on unmount.

SSR Safety

  • Safe to use during server-side rendering: when window is undefined it returns { width: 0, height: 0 }.
  • After hydration it corrects the values to the real window size using useLayoutEffect, avoiding a visible flicker.