Skip to main content

useResizeObserver

The useResizeObserver hook tracks the dimensions of a DOM element using the Resize Observer API. Updates reactively whenever the element is resized.

Usage

Installation

import { useResizeObserver } from "hookstorm";

Parameters

  • target — A ref pointing to the element to observe.

Return Values

PropertyTypeDescription
widthnumberCurrent content width of the element in pixels.
heightnumberCurrent content height of the element in pixels.
entryResizeObserverEntry | nullThe latest observer entry, or null before first observation.

Example Usage

import { useRef, ReactElement } from "react";
import { useResizeObserver } from "hookstorm";

export default function ResizablePanel(): ReactElement {
const ref = useRef<HTMLDivElement>(null);
const { width, height } = useResizeObserver(ref);

return (
<div ref={ref} style={{ resize: "both", overflow: "auto", minWidth: 100 }}>
<p>
{width.toFixed(0)} × {height.toFixed(0)} px
</p>
</div>
);
}

Notes

  • The observer is automatically disconnected on component unmount.
  • If target.current is null when the effect runs, no observer is created.
  • width and height reflect the element's contentRect, which excludes padding and border.