React Resize Detector Hook
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
-
TypeError: (0 , react_resize_detector_1.useResizeDetector) is not a function
cause Attempting to use `require()` for a pure ESM module, or incorrect import configuration in a CommonJS environment after upgrading to v12.fixEnsure your project is configured for ES modules (e.g., `"type": "module"` in `package.json`). Change `const { useResizeDetector } = require('react-resize-detector');` to `import { useResizeDetector } from 'react-resize-detector';`. -
Error: Invalid hook call. Hooks can only be called inside of the body of a function component.
cause Attempting to use `useResizeDetector` in a class component or outside of a React functional component lifecycle.fixEnsure `useResizeDetector` is only called at the top level of your React functional components or custom hooks. For class components, consider refactoring to functional components or using a wrapper. -
TS2345: Argument of type '(width: number, height: number) => void' is not assignable to parameter of type 'OnResizeCallback'.
cause Using the old `onResize` callback signature after upgrading to v11 or higher.fixUpdate your `onResize` callback signature from `(width, height) => { ... }` to `({ width, height, entry }) => { ... }`.
Warnings
- breaking Version 12.0.0 migrated the module to be pure ESM. CommonJS `require()` statements will no longer work and will cause runtime errors.
- breaking The `onResize` callback signature changed in v11.0.0. It now receives a single object with `width`, `height`, and `entry` properties, instead of separate `width` and `height` arguments.
- breaking Starting with version 10.0.0, the library dropped support for all methods except the `useResizeObserver` hook. Legacy component-based APIs (like `withResizeDetector` HOC or render prop component) are no longer available.
- breaking Version 10.0.0 dropped support for React 16 and 17. The library now requires React 18 or 19.
- gotcha When using an external ref (`targetRef` prop), be aware that dynamically mounting and unmounting the observed element can lead to unexpected behavior. The library advises against this advanced approach unless necessary.
Install
-
npm install react-resize-detector -
yarn add react-resize-detector -
pnpm add react-resize-detector
Imports
- useResizeDetector
const useResizeDetector = require('react-resize-detector');import { useResizeDetector } from 'react-resize-detector'; - OnResizeCallback
import { OnResizeCallback } from 'react-resize-detector'; - useResizeDetector with type argument
import { useResizeDetector } from 'react-resize-detector'; const { ref } = useResizeDetector<HTMLDivElement>();
Quickstart
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;