-
-
Notifications
You must be signed in to change notification settings - Fork 3.2k
/
Copy pathuseMeasureDirty.ts
52 lines (43 loc) · 1019 Bytes
/
useMeasureDirty.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import { RefObject, useEffect, useRef, useState } from 'react';
import ResizeObserver from 'resize-observer-polyfill';
export interface ContentRect {
width: number;
height: number;
top: number;
right: number;
left: number;
bottom: number;
}
const useMeasureDirty = (ref: RefObject<HTMLElement>): ContentRect => {
const frame = useRef(0);
const [rect, set] = useState({
width: 0,
height: 0,
top: 0,
left: 0,
bottom: 0,
right: 0,
});
const [observer] = useState(
() =>
new ResizeObserver((entries) => {
const entry = entries[0];
if (entry) {
cancelAnimationFrame(frame.current);
frame.current = requestAnimationFrame(() => {
if (ref.current) {
set(entry.contentRect);
}
});
}
})
);
useEffect(() => {
observer.disconnect();
if (ref.current) {
observer.observe(ref.current);
}
}, [ref]);
return rect;
};
export default useMeasureDirty;