React useResizeObserver Hook
React useResizeObserver hook for element resize detection. Monitor DOM element size changes with ResizeObserver API and TypeScript support for Next.js apps.
Struggling with element resize detection?
Join our Discord community for help from other developers.
Ever tried to track element size changes in React and ended up with window.resize event chaos, getBoundingClientRect polling nightmares, or broken responsive components? You know the drill—manually listening to window resize events that don't catch container changes, polling element dimensions with performance issues, dealing with layout thrashing from constant DOM measurements. This free open source React useResizeObserver custom hook handles all that element size tracking complexity so you can focus on building responsive features instead of debugging measurement edge cases in your React applications.
useResizeObserver showcase
Real-time element size tracking with ResizeObserver API:
This free open source React hook simplifies element resize detection with TypeScript support for modern JavaScript applications. Whether you're building responsive charts, adaptive layouts, or dynamic modals in your Next.js projects, this React hook keeps your size tracking accurate and performant.
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
Why most resize detection implementations suck
Look, you could keep using window.resize listeners and manual getBoundingClientRect calls. But then you hit the resize detection complexity—window events don't catch container size changes, DOM measurement queries cause layout thrashing, performance issues from constant polling in React applications.
Most developers use window.resize events that only fire when the browser window changes, missing crucial element-level resizing from content updates or CSS animations in TypeScript components. Or they poll element dimensions with getBoundingClientRect(), causing performance bottlenecks and layout thrashing from constant DOM queries. Some create custom solutions without proper cleanup, leading to memory leaks when components unmount in Next.js projects.
This React hook uses the native ResizeObserver API under the hood, which is specifically designed for efficient element size monitoring in JavaScript applications. The browser handles all the optimization, plus you get precise element-level detection instead of just window changes.
Plus it handles all the edge cases—SSR compatibility with proper fallbacks, multiple box model support, automatic cleanup and memory leak prevention in React development. No more scattered resize listeners or performance bottlenecks from DOM polling.
This free open source React hook manages element size state while you focus on building features. Whether you're creating React applications, Next.js dashboards, or TypeScript components, reliable resize detection keeps your JavaScript development responsive.
Features
- ResizeObserver API providing native browser performance for element size observation in React applications
- Multiple box models supporting content-box, border-box, and device-pixel-content-box measurements in TypeScript components
- Performance optimized with debounced callbacks and memory leak prevention in Next.js projects
- TypeScript generics with type-safe element references and size objects for JavaScript development
- SSR compatibility with proper server-side rendering support and hydration safety in React frameworks
- Browser fallbacks handling legacy browser support and polyfill requirements in modern applications
- Free open source designed for modern React development workflows
When you'll actually use this
Real talk—this isn't for basic responsive design in React applications. CSS media queries handle most layout cases perfectly. But when you need element-specific size detection for dynamic content or JavaScript-driven layouts, this React hook delivers in Next.js projects.
Perfect for:
- Responsive charts - Resize data visualizations when container dimensions change built with TypeScript
- Adaptive grids - Adjust column counts and layouts based on available space using React patterns
- Modal positioning - Reposition dialogs and popovers when content size changes in JavaScript applications
- Canvas scaling - Maintain aspect ratios and pixel density for graphics rendering in React components
- Dynamic typography - Adjust font sizes based on container width constraints in Next.js applications
- Masonry layouts - Recalculate item positions when container or item sizes change using TypeScript safety
API Reference
useResizeObserver
useResizeObserver<T extends HTMLElement = HTMLElement>(
options: UseResizeObserverOptions<T>
): UseResizeObserverReturn
Parameter | Type | Description |
---|---|---|
options | UseResizeObserverOptions<T> | 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 | Use Case |
---|---|---|
'content-box' | Measures content area excluding padding and border | Text content, inner layouts |
'border-box' | Measures total element size including padding and border | Full component sizing |
'device-pixel-content-box' | Device pixel ratio adjusted content measurements | High-DPI graphics, canvas |
Return Value
Property | Type | Description |
---|---|---|
width | number | undefined | Current width of the observed element in pixels |
height | number | undefined | Current height of the observed element in pixels |
Common gotchas
ResizeObserver needs polyfill for old browsers: Most modern browsers support ResizeObserver natively, but older browsers need a polyfill in React applications. The React hook gracefully handles missing ResizeObserver by returning undefined dimensions.
Box model choice affects measurements: Choose 'content-box' for inner content sizing, 'border-box' for total element size including padding/borders, or 'device-pixel-content-box' for high-DPI graphics work in TypeScript components.
Cleanup is automatic but refs matter: The React hook automatically disconnects observers when components unmount or refs change in Next.js projects. Make sure your ref is stable to avoid unnecessary observer recreation.
SSR returns undefined initially: Dimensions start as undefined on the server and populate after hydration in JavaScript applications. Always handle the undefined state in your components.
Performance with many observers: Multiple ResizeObserver instances can impact performance in React frameworks. Consider consolidating observations or using a single observer for multiple elements when possible.
Box model browser support: Some box models like 'device-pixel-content-box' have limited browser support in TypeScript projects. Always provide fallbacks for better compatibility.
Related hooks you will also like
useWindowSize
Window size tracking for viewport-level resize detection
useIntersectionObserver
Element visibility detection that complements size observations
useEventListener
Event handling foundation for resize and DOM events
useMediaQuery
Responsive breakpoint detection for size-based logic
useIsClient
Client detection needed for safe DOM size measurements
useDebounceCallback
Debounced callbacks for expensive resize calculations
Questions you might have
React useReadLocalStorage Hook
React useReadLocalStorage hook for localStorage reading. Get reactive values with cross-tab synchronization and SSR support using TypeScript for Next.js.
React useScreen Hook
React useScreen hook for screen information tracking. Monitor display dimensions, orientation, and capabilities with TypeScript support for Next.js apps.