useResizeObserver
A React hook that tracks element size changes using ResizeObserver, providing detailed information about content, border, and device pixel sizes.
Demo
1. Resizable Box with Detailed Metrics
Content Box
Border Box
Content Box Size
2. Responsive Grid
Installation
npm install @thibault.sh/hooks
Usage
import { useResizeObserver } from "@thibault.sh/hooks";
function ResponsiveComponent() {
const elementRef = useRef(null);
const entry = useResizeObserver(elementRef);
// Access different size measurements
const { width, height } = entry?.contentRect ?? { width: 0, height: 0 };
const contentSize = entry?.contentBoxSize[0];
const borderSize = entry?.borderBoxSize[0];
return (
<div ref={elementRef}>
Content Size: {width}x{height}
Border Size: {borderSize?.inlineSize}x{borderSize?.blockSize}
</div>
);
}
API Reference
Returns
Latest ResizeObserverEntry if available, null otherwise
Return Value
Returns a ResizeObserverEntry object or null. The entry object provides detailed information about the observed element's dimensions in different contexts.
contentRect
A DOMRectReadOnly object containing the element's content box dimensions:
- width: The width of the content box
- height: The height of the content box
- x/y: The coordinates relative to the viewport
- top/right/bottom/left: The edges relative to the viewport
contentBoxSize
An array of ResizeObserverSize objects describing the element's content box:
- inlineSize: The size in the element's inline direction (usually width)
- blockSize: The size in the element's block direction (usually height)
borderBoxSize
An array of ResizeObserverSize objects describing the element's border box:
- inlineSize: The size including padding and border in the inline direction
- blockSize: The size including padding and border in the block direction
devicePixelContentBoxSize
An array of ResizeObserverSize objects describing the element's content box in device pixels:
- inlineSize: The size in device pixels in the inline direction
- blockSize: The size in device pixels in the block direction
Features
Detailed Size Information
Access comprehensive size measurements including content box, border box, and device pixel sizes for precise layout control.
Responsive Layouts
Create dynamic layouts that adapt to container size changes, perfect for building responsive components and grids.
Real-time Updates
Get immediate feedback on size changes, enabling smooth transitions and dynamic adjustments to your UI.
Performance Optimized
Uses the native ResizeObserver API for efficient size tracking without polling or layout thrashing.