Join our Discord Community

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.

Loading component...

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

Loading component...

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

ParameterTypeDefaultDescription
optionsUseResizeObserverOptions<T>requiredConfiguration object for the resize observer

UseResizeObserverOptions

PropertyTypeDefaultDescription
refRefObject<T>requiredReact ref of the element to observe
onResize(size: Size) => voidundefinedCallback for handling resize events (prevents re-renders)
boxBoxModel'content-box'Box model to use for measurements

Box Model Types

TypeDescription
'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

PropertyTypeDescription
widthnumber | undefinedCurrent width of the observed element
heightnumber | undefinedCurrent height of the observed element

Size Object

PropertyTypeDescription
widthnumber | undefinedElement width in pixels
heightnumber | undefinedElement 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