0
# React Resize Detector
1
2
React Resize Detector is a modern hook-based library that provides element size change detection using the native ResizeObserver API. It enables React applications to respond to element resizing without relying on window resize listeners or polling timeouts.
3
4
## Package Information
5
6
- **Package Name**: react-resize-detector
7
- **Package Type**: npm
8
- **Language**: TypeScript
9
- **Installation**: `npm install react-resize-detector`
10
11
## Core Imports
12
13
```typescript
14
import { useResizeDetector } from "react-resize-detector";
15
```
16
17
For CommonJS:
18
19
```javascript
20
const { useResizeDetector } = require("react-resize-detector");
21
```
22
23
Type imports:
24
25
```typescript
26
import type {
27
UseResizeDetectorReturn,
28
useResizeDetectorProps,
29
OnResizeCallback,
30
ResizePayload,
31
RefreshModeType,
32
RefreshOptionsType,
33
Dimensions,
34
OnRefChangeType,
35
} from "react-resize-detector";
36
```
37
38
> **Note**: `OnRefChangeType` may not be directly importable in some versions as it's not explicitly re-exported from the main index. It's used in the `UseResizeDetectorReturn` interface but may require TypeScript's type inference to access.
39
40
## Basic Usage
41
42
```typescript
43
import { useResizeDetector } from "react-resize-detector";
44
45
const MyComponent = () => {
46
const { width, height, ref } = useResizeDetector<HTMLDivElement>();
47
return <div ref={ref}>{`${width}x${height}`}</div>;
48
};
49
```
50
51
## Architecture
52
53
React Resize Detector is built around:
54
55
- **ResizeObserver Integration**: Uses the native ResizeObserver API for efficient element size monitoring
56
- **React Hook Pattern**: Provides a clean, declarative API through the `useResizeDetector` hook
57
- **Performance Optimization**: Includes rate limiting (throttle/debounce), selective dimension tracking, and render control
58
- **Type Safety**: Full TypeScript support with generic type parameters for HTML elements
59
- **Flexible Ref Handling**: Supports both internal ref creation and external ref attachment
60
61
## Capabilities
62
63
### Resize Detection Hook
64
65
The main hook for detecting element resize events using ResizeObserver API.
66
67
```typescript { .api }
68
/**
69
* React hook for detecting element resize events
70
* @param props - Configuration options for resize detection
71
* @returns Object containing dimensions and ref to attach to DOM element
72
*/
73
function useResizeDetector<T extends HTMLElement = HTMLElement>(
74
props?: useResizeDetectorProps<T>
75
): UseResizeDetectorReturn<T>;
76
77
interface useResizeDetectorProps<T extends HTMLElement> {
78
/** Callback invoked with resize information */
79
onResize?: OnResizeCallback;
80
/** Trigger updates on width changes (default: true) */
81
handleWidth?: boolean;
82
/** Trigger updates on height changes (default: true) */
83
handleHeight?: boolean;
84
/** Skip the first resize event when component mounts (default: false) */
85
skipOnMount?: boolean;
86
/** Disable re-renders triggered by the hook, only call onResize (default: false) */
87
disableRerender?: boolean;
88
/** Rate limiting strategy ('throttle' | 'debounce') */
89
refreshMode?: RefreshModeType;
90
/** Delay in milliseconds for rate limiting (default: 1000) */
91
refreshRate?: number;
92
/** Additional options for throttle/debounce */
93
refreshOptions?: RefreshOptionsType;
94
/** Options passed to ResizeObserver.observe() */
95
observerOptions?: ResizeObserverOptions;
96
/** External ref to observe (use with caution) */
97
targetRef?: React.MutableRefObject<T | null>;
98
}
99
100
interface UseResizeDetectorReturn<T> extends Dimensions {
101
/** Ref to attach to DOM element for resize observation */
102
ref: OnRefChangeType<T>;
103
}
104
```
105
106
**Usage Examples:**
107
108
```typescript
109
// Basic usage
110
const { width, height, ref } = useResizeDetector<HTMLDivElement>();
111
112
// With resize callback
113
const { width, height, ref } = useResizeDetector<HTMLDivElement>({
114
onResize: ({ width, height, entry }) => {
115
console.log('Resized to:', width, height);
116
}
117
});
118
119
// Performance optimized
120
const { width, ref } = useResizeDetector<HTMLDivElement>({
121
handleHeight: false, // Only track width
122
refreshMode: 'debounce',
123
refreshRate: 100,
124
observerOptions: { box: 'border-box' }
125
});
126
127
// External ref usage
128
import { useRef } from 'react';
129
const targetRef = useRef<HTMLDivElement>(null);
130
const { width, height } = useResizeDetector({ targetRef });
131
```
132
133
### Resize Callback Types
134
135
Types for handling resize events and callbacks.
136
137
```typescript { .api }
138
/**
139
* Callback function invoked when element is resized
140
* @param payload - Resize information containing dimensions and ResizeObserverEntry
141
*/
142
type OnResizeCallback = (payload: ResizePayload) => void;
143
144
/**
145
* Payload passed to onResize callback
146
* Contains element dimensions or null if element is unmounted
147
*/
148
type ResizePayload =
149
| { width: number; height: number; entry: ResizeObserverEntry }
150
| { width: null; height: null; entry: null };
151
```
152
153
### Rate Limiting Configuration
154
155
Types for configuring performance optimization through rate limiting.
156
157
```typescript { .api }
158
/** Rate limiting strategy options */
159
type RefreshModeType = 'throttle' | 'debounce';
160
161
/** Additional options for throttle/debounce behavior */
162
type RefreshOptionsType = {
163
/** Execute on the leading edge of the delay (default: false for debounce, true for throttle) */
164
leading?: boolean;
165
/** Execute on the trailing edge of the delay (default: true) */
166
trailing?: boolean;
167
};
168
```
169
170
### Dimension Types
171
172
Types for representing element dimensions.
173
174
```typescript { .api }
175
/** Element dimension values */
176
type Dimensions = {
177
/** Element height in pixels */
178
height?: number;
179
/** Element width in pixels */
180
width?: number;
181
};
182
183
/**
184
* Ref callback function type with current property
185
* Can be called as function or accessed via .current property
186
*/
187
type OnRefChangeType<T> = {
188
(node: T | null): void;
189
current?: T | null;
190
};
191
```
192
193
## Advanced Usage Examples
194
195
### Responsive Component
196
197
```typescript
198
import { useResizeDetector } from "react-resize-detector";
199
200
const ResponsiveCard = () => {
201
const { width, ref } = useResizeDetector<HTMLDivElement>();
202
203
const cardStyle = {
204
padding: width && width > 600 ? '2rem' : '1rem',
205
fontSize: width && width > 400 ? '1.2em' : '1em',
206
flexDirection: width && width > 500 ? 'row' : 'column',
207
};
208
209
return (
210
<div ref={ref} style={cardStyle}>
211
<h2>Responsive Card</h2>
212
<p>Width: {width}px</p>
213
</div>
214
);
215
};
216
```
217
218
### Chart Resizing with Debouncing
219
220
```typescript
221
import { useResizeDetector } from "react-resize-detector";
222
import { useCallback, useEffect, useRef } from "react";
223
224
const Chart = () => {
225
const canvasRef = useRef<HTMLCanvasElement>(null);
226
const { width, height, ref } = useResizeDetector<HTMLCanvasElement>({
227
refreshMode: 'debounce',
228
refreshRate: 100,
229
});
230
231
// Merge refs to both track resize and access canvas element
232
const mergedRef = useCallback((node: HTMLCanvasElement | null) => {
233
canvasRef.current = node;
234
ref(node);
235
}, [ref]);
236
237
useEffect(() => {
238
if (width && height && canvasRef.current) {
239
// Redraw chart with new dimensions
240
redrawChart(canvasRef.current, width, height);
241
}
242
}, [width, height]);
243
244
return <canvas ref={mergedRef} />;
245
};
246
```
247
248
### Performance Optimization
249
250
```typescript
251
import { useResizeDetector } from "react-resize-detector";
252
253
const OptimizedComponent = () => {
254
const { width, ref } = useResizeDetector<HTMLDivElement>({
255
// Only track width changes for better performance
256
handleHeight: false,
257
// Debounce rapid changes
258
refreshMode: 'debounce',
259
refreshRate: 150,
260
// Skip initial mount calculation
261
skipOnMount: true,
262
// Use border-box for more accurate measurements
263
observerOptions: { box: 'border-box' },
264
});
265
266
return <div ref={ref}>Optimized: {width}px wide</div>;
267
};
268
```
269
270
### Disable Re-renders
271
272
```typescript
273
import { useResizeDetector } from "react-resize-detector";
274
275
const NonRerenderingComponent = () => {
276
const { ref } = useResizeDetector<HTMLDivElement>({
277
// Disable re-renders triggered by the hook
278
disableRerender: true,
279
// Handle resize events through callback only
280
onResize: ({ width, height }) => {
281
// Update external state or perform side effects
282
// without causing component re-renders
283
console.log('Resized to:', width, height);
284
},
285
});
286
287
return <div ref={ref}>This component won't re-render on resize</div>;
288
};
289
```
290
291
## Browser Compatibility
292
293
- ✅ Chrome 64+
294
- ✅ Firefox 69+
295
- ✅ Safari 13.1+
296
- ✅ Edge 79+
297
298
For older browsers, consider using a [ResizeObserver polyfill](https://github.com/que-etc/resize-observer-polyfill).
299
300
## Dependencies
301
302
- **React**: ^18.0.0 || ^19.0.0 (peer dependency)
303
- **es-toolkit**: ^1.39.6 (for throttle/debounce utilities)