React Resize Detector Hook

12.3.0 · active · verified Sun Apr 19

react-resize-detector is a React library that leverages the native `ResizeObserver` API to detect element size changes within React applications. It provides a `useResizeDetector` hook for integrating resize observation directly into functional components. The current stable version is 12.3.0. Releases are somewhat frequent, with multiple major versions (v10, v11, v12) released within the last year, indicating active development and occasional breaking changes. Key differentiators include its small bundle size (~2kb), TypeScript support, and reliance on native `ResizeObserver` over `window.resize` listeners or timeouts, offering performant and accurate resize detection. The library is designed for scenarios requiring JavaScript-based resize logic, complex dimension-based calculations, or integration with React state/effects, differentiating itself from purely CSS-based container queries.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates basic usage of `useResizeDetector` with an `onResize` callback to log dimensions, debounce updates, and attach the observer to a div element.

import { useCallback } from 'react';
import { useResizeDetector, OnResizeCallback } from 'react-resize-detector';

const MyResizableComponent = () => {
  const onResize: OnResizeCallback = useCallback((payload) => {
    if (payload.width !== null && payload.height !== null) {
      console.log('Component dimensions:', payload.width, 'x', payload.height);
      // Perform complex calculations or update state here
    } else {
      console.log('Element unmounted or dimensions not available.');
    }
  }, []);

  const { width, height, ref } = useResizeDetector<HTMLDivElement>({
    onResize,
    refreshMode: 'debounce', // Optional: 'throttle', 'debounce', or 'resize' (default)
    refreshRate: 100 // Optional: milliseconds for throttle/debounce
  });

  return (
    <div ref={ref} style={{ border: '1px solid blue', padding: '20px', minWidth: '100px', minHeight: '100px' }}>
      <p>Current size: {width}x{height}</p>
      <p>Resize your browser window or this container to see changes.</p>
    </div>
  );
};

export default MyResizableComponent;

view raw JSON →