What is react-resize-detector?
The react-resize-detector is a React component designed to handle resize events for React elements. It provides a simple and efficient way to trigger a function or render logic when the size of an element changes. This is particularly useful in responsive designs and when elements need to adjust based on their container's dimensions.
What are react-resize-detector's main functionalities?
Basic resize detection
This feature allows you to detect the size of a component and react to changes. The `useResizeDetector` hook provides `width`, `height`, and `ref` which you attach to the component you want to monitor. The component re-renders whenever the size changes, displaying the new dimensions.
import React from 'react';
import useResizeDetector from 'react-resize-detector';
const ResponsiveComponent = () => {
const { width, height, ref } = useResizeDetector();
return (
<div ref={ref}>
Size: {width} x {height}
</div>
);
};
export default ResponsiveComponent;
OnResize callback
This feature uses the `withResizeDetector` higher-order component to monitor size changes. It provides `width`, `height`, and an `onResize` callback that is triggered on every resize event. This is useful for performing actions or calculations based on the new size.
import React from 'react';
import { withResizeDetector } from 'react-resize-detector';
class MyComponent extends React.Component {
render() {
const { width, height, onResize } = this.props;
return (
<div onResize={onResize}>
Current size: {width} x {height}
</div>
);
}
}
export default withResizeDetector(MyComponent, {
handleWidth: true,
handleHeight: true,
onResize: (width, height) => console.log(`Resized to ${width} x ${height}`)
});
Other packages similar to react-resize-detector
react-sizeme
react-sizeme is another package that provides similar functionality to react-resize-detector. It allows components to respond to changes in size. However, react-sizeme uses a higher-order component approach primarily, which might be less convenient than hooks provided by react-resize-detector in functional components.
resize-observer-polyfill
This package is a polyfill for the ResizeObserver API, which is used to report changes to the dimensions of an Element's content or border box. It's more of a low-level API compared to react-resize-detector, which provides React-specific abstractions and hooks for easier integration in React applications.
Handle element resizes like it's 2025!

Modern browsers now have native support for detecting element size changes through ResizeObservers. This library utilizes ResizeObservers to facilitate managing element size changes in React applications.
🐥 Tiny ~2kb
🐼 Written in TypeScript
🐠 Used by 170k repositories
🦄 Produces 100 million downloads annually
No window.resize
listeners! No timeouts!
Should you use this library?
Consider CSS Container Queries first! They now work in all major browsers and might solve your use case with pure CSS.
CSS Container Queries Example
<div class="post">
<div class="card">
<h2>Card title</h2>
<p>Card content</p>
</div>
</div>
.post {
container-type: inline-size;
}
.card h2 {
font-size: 1em;
}
@container (min-width: 700px) {
.card h2 {
font-size: 2em;
}
}
Use this library when you need:
- JavaScript-based resize logic with full TypeScript support
- Complex calculations based on dimensions
- Integration with React state/effects
- Programmatic control over resize behavior
Installation
npm install react-resize-detector
yarn add react-resize-detector
pnpm add react-resize-detector
Quick Start
Basic Usage
import { useResizeDetector } from 'react-resize-detector';
const CustomComponent = () => {
const { width, height, ref } = useResizeDetector<HTMLDivElement>();
return <div ref={ref}>{`${width}x${height}`}</div>;
};
With Resize Callback
import { useCallback } from 'react';
import { useResizeDetector, OnResizeCallback } from 'react-resize-detector';
const CustomComponent = () => {
const onResize: OnResizeCallback = useCallback((payload) => {
if (payload.width !== null && payload.height !== null) {
console.log('Dimensions:', payload.width, payload.height);
} else {
console.log('Element unmounted');
}
}, []);
const { width, height, ref } = useResizeDetector<HTMLDivElement>({
onResize,
});
return <div ref={ref}>{`${width}x${height}`}</div>;
};
With External Ref (Advanced)
It's not advised to use this approach, as dynamically mounting and unmounting the observed element could lead to unexpected behavior.
import { useRef } from 'react';
import { useResizeDetector } from 'react-resize-detector';
const CustomComponent = () => {
const targetRef = useRef<HTMLDivElement>(null);
const { width, height } = useResizeDetector({ targetRef });
return <div ref={targetRef}>{`${width}x${height}`}</div>;
};
API Reference
Hook Signature
useResizeDetector<T extends HTMLElement = HTMLElement>(
props?: useResizeDetectorProps<T>
): UseResizeDetectorReturn<T>
Props
onResize | (payload: ResizePayload) => void | Callback invoked with resize information | undefined |
handleWidth | boolean | Trigger updates on width changes | true |
handleHeight | boolean | Trigger updates on height changes | true |
skipOnMount | boolean | Skip the first resize event when component mounts | false |
disableRerender | boolean | Disable re-renders triggered by the hook. Only the onResize callback will be called | false |
refreshMode | 'throttle' | 'debounce' | Rate limiting strategy. See es-toolkit docs | undefined |
refreshRate | number | Delay in milliseconds for rate limiting | 1000 |
refreshOptions | { leading?: boolean; trailing?: boolean } | Additional options for throttle/debounce | undefined |
observerOptions | ResizeObserverOptions | Options passed to resizeObserver.observe | undefined |
targetRef | MutableRefObject<T | null> | External ref to observe (use with caution) | undefined |
Advanced Examples
Responsive Component
import { useResizeDetector } from 'react-resize-detector';
const ResponsiveCard = () => {
const { width, ref } = useResizeDetector();
const cardStyle = {
padding: width > 600 ? '2rem' : '1rem',
fontSize: width > 400 ? '1.2em' : '1em',
flexDirection: width > 500 ? 'row' : 'column',
};
return (
<div ref={ref} style={cardStyle}>
<h2>Responsive Card</h2>
<p>Width: {width}px</p>
</div>
);
};
Chart Resizing
import { useResizeDetector } from 'react-resize-detector';
import { useEffect, useRef } from 'react';
const Chart = () => {
const chartRef = useRef(null);
const { width, height, ref } = useResizeDetector({
refreshMode: 'debounce',
refreshRate: 100,
});
useEffect(() => {
if (width && height && chartRef.current) {
redrawChart(chartRef.current, width, height);
}
}, [width, height]);
return <canvas ref={ref} />;
};
Performance Optimization
import { useResizeDetector } from 'react-resize-detector';
const OptimizedComponent = () => {
const { width, height, ref } = useResizeDetector({
handleHeight: false,
refreshMode: 'debounce',
refreshRate: 150,
skipOnMount: true,
observerOptions: { box: 'border-box' },
});
return <div ref={ref}>Optimized: {width}px wide</div>;
};
Disable Re-renders
import { useResizeDetector } from 'react-resize-detector';
const NonRerenderingComponent = () => {
const { ref } = useResizeDetector({
disableRerender: true,
onResize: ({ width, height }) => {
console.log('Resized to:', width, height);
},
});
return <div ref={ref}>This component won't re-render on resize</div>;
};
Browser Support
- ✅ Chrome 64+
- ✅ Firefox 69+
- ✅ Safari 13.1+
- ✅ Edge 79+
For older browsers, consider using a ResizeObserver polyfill.
Testing
const { ResizeObserver } = window;
beforeEach(() => {
delete window.ResizeObserver;
window.ResizeObserver = jest.fn().mockImplementation(() => ({
observe: jest.fn(),
unobserve: jest.fn(),
disconnect: jest.fn(),
}));
});
afterEach(() => {
window.ResizeObserver = ResizeObserver;
jest.restoreAllMocks();
});
Performance Tips
- Use
handleWidth
/handleHeight: false
if you only need one dimension
- Enable
skipOnMount: true
if you don't need initial measurements
- Use
debounce
or throttle
for expensive resize handlers
- Specify
observerOptions.box
for consistent measurements
License
MIT
❤️ Support
Show us some love and STAR ⭐ the project if you find it useful