-
Notifications
You must be signed in to change notification settings - Fork 0
useResizeObserver
A highly optimized hook that leverages the native browser ResizeObserver API to detect when a specific DOM element changes its dimensions. Unlike standard window resize listeners, this hook detects size changes triggered by dynamic content, CSS animations, or Flexbox/Grid layout shifts.
Tip
If you only need the raw width and height, consider using the simpler useElementSize hook instead. useResizeObserver is for advanced use cases where you need the full ResizeObserverEntry object.
Listening to a div element's resize events and rendering its exact width and height.
import { useRef } from "react";
import { useResizeObserver } from "react-hook-lab";
function ResizableBox() {
const boxRef = useRef<HTMLDivElement>(null);
// Instantly tracks dimensions, even if resized via CSS resize: "both"
const { width, height } = useResizeObserver(boxRef);
return (
<div
ref={boxRef}
style={{ resize: 'both', overflow: 'auto', border: '1px solid black' }}
>
<p>I am {width}px by {height}px.</p>
</div>
);
}Accessing the underlying ResizeObserverEntry to get advanced layout metrics.
import { useRef } from "react";
import { useResizeObserver } from "react-hook-lab";
function AdvancedMetrics() {
const containerRef = useRef<HTMLDivElement>(null);
// Extracts the raw entry object provided by the browser API
const { entry } = useResizeObserver(containerRef);
return (
<div ref={containerRef}>
<pre>
{JSON.stringify({
x: entry?.contentRect.x,
y: entry?.contentRect.y,
top: entry?.contentRect.top,
left: entry?.contentRect.left,
}, null, 2)}
</pre>
</div>
);
}Changing the observer's box tracking mode (e.g., tracking the border-box instead of the content-box).
import { useRef } from "react";
import { useResizeObserver } from "react-hook-lab";
function BorderBoxTracker() {
const boxRef = useRef<HTMLDivElement>(null);
// Tells the browser to track the outer dimensions including padding and borders
const { width } = useResizeObserver(boxRef, { box: "border-box" });
return (
<div
ref={boxRef}
style={{ padding: "50px", border: "10px solid red", width: "50%" }}
>
Border-box Width: {width}px
</div>
);
}-
ref- Type:
RefObject<HTMLElement> - Description: The React ref attached to the DOM element you want to measure.
- Type:
-
options(Optional)- Type:
UseResizeObserverOptions - Description: Configures the internal
ResizeObserver.
- Type:
export interface UseResizeObserverOptions {
// "content-box" (default), "border-box", or "device-pixel-content-box"
box?: ResizeObserverBoxOptions;
}Returns an object of type UseResizeObserverReturn containing:
-
width(number): The exact pixel width of the element. -
height(number): The exact pixel height of the element. -
size({ width: number; height: number }): A convenient grouped object of the dimensions. -
entry(ResizeObserverEntry | undefined): The raw object emitted by the browser, containing deep metrics likecontentRectanddevicePixelContentBoxSize.
When initialized, useResizeObserver constructs a native new ResizeObserver() tied directly to your ref.current.
When the browser's layout engine detects a dimension change on that specific element (independent of the global window size), the observer callback fires. The hook extracts the contentRect.width and contentRect.height and compares them against the previous React state. If (and only if) the pixel values have genuinely changed, it updates the state, triggering a re-render. It aggressively cleans up and disconnects the observer when the component unmounts.
Built with ❤️ by Saurav-TB-Pandey. | Report an Issue | NPM