useResizeObserver
Custom hook that observes the size of an element using the ResizeObserver API. Perfect for responsive React applications requiring dynamic layout adjustments with Next.js integration and TypeScript support.
Installation
npx shadcn@latest add https://www.shadcn.io/registry/use-resize-observer.json
npx shadcn@latest add https://www.shadcn.io/registry/use-resize-observer.json
pnpm dlx shadcn@latest add https://www.shadcn.io/registry/use-resize-observer.json
bunx shadcn@latest add https://www.shadcn.io/registry/use-resize-observer.json
Features
- ResizeObserver API providing native browser performance for element size observation
- Multiple box models supporting content-box, border-box, and device-pixel-content-box measurements
- Debounced callbacks allowing custom resize handlers with performance optimization
- TypeScript generics with type-safe element references and size objects
- SSR compatibility with proper server-side rendering support and hydration safety
- Memory leak prevention using proper cleanup and useIsMounted integration
- shadcn/ui integration ideal for responsive components and layout systems
Examples
Advanced Configuration with Debouncing
Demonstrates different box models and debounced resize handling for performance optimization.
Use Cases
This free open source React component works well for:
- Responsive layouts - Adjust component sizing based on container dimensions with Next.js
- Chart rendering - Resize charts and graphs when container changes using TypeScript
- Modal positioning - Update dialog placement based on viewport changes with shadcn/ui
- Grid systems - Dynamic column adjustments for responsive card layouts using Tailwind CSS
- Canvas sizing - Maintain canvas aspect ratios with container size changes
API Reference
useResizeObserver
Parameter | Type | Default | Description |
---|---|---|---|
options | UseResizeObserverOptions<T> | required | Configuration object for the resize observer |
UseResizeObserverOptions
Property | Type | Default | Description |
---|---|---|---|
ref | RefObject<T> | required | React ref of the element to observe |
onResize | (size: Size) => void | undefined | Callback for handling resize events (prevents re-renders) |
box | BoxModel | 'content-box' | Box model to use for measurements |
Box Model Types
Type | Description |
---|---|
'content-box' | Measures content area excluding padding and border |
'border-box' | Measures total element size including padding and border |
'device-pixel-content-box' | Device pixel ratio adjusted content measurements |
Return Value
Property | Type | Description |
---|---|---|
width | number | undefined | Current width of the observed element |
height | number | undefined | Current height of the observed element |
Size Object
Property | Type | Description |
---|---|---|
width | number | undefined | Element width in pixels |
height | number | undefined | Element height in pixels |
Usage Patterns
Basic Size Observation
import { useResizeObserver } from '@repo/use-resize-observer';
function ResponsiveComponent() {
const ref = useRef<HTMLDivElement>(null);
const { width, height } = useResizeObserver({ ref });
return (
<div ref={ref}>
Size: {width} × {height}
</div>
);
}
With Custom Resize Handler
const onResize = useCallback((size: Size) => {
console.log('Element resized:', size);
}, []);
useResizeObserver({
ref: elementRef,
onResize,
box: 'border-box'
});
Debounced Resize Handling
import { useDebounceCallback } from '@repo/use-debounce-callback';
const debouncedResize = useDebounceCallback((size: Size) => {
updateLayout(size);
}, 150);
useResizeObserver({
ref: containerRef,
onResize: debouncedResize
});
Implementation Notes
- Uses native ResizeObserver API for optimal performance and accuracy
- Automatically handles SSR scenarios where ResizeObserver is not available
- Prevents memory leaks by checking component mount status before state updates
- Supports Firefox's non-standard ResizeObserver implementation for compatibility
- When using
onResize
callback, the hook doesn't trigger re-renders for better performance - Size values are
undefined
initially until first measurement is available - Cleanup is handled automatically when component unmounts or ref changes
- Compatible with all modern browsers that support ResizeObserver API
useReadLocalStorage
React hook that reads a value from localStorage with automatic updates, cross-tab synchronization, and SSR compatibility.
useScreen
Custom hook that tracks the screen dimensions and properties with debouncing support. Perfect for responsive React applications requiring display information with Next.js integration and TypeScript support.