-
Notifications
You must be signed in to change notification settings - Fork 96
/
Copy pathindex.ts
34 lines (28 loc) · 1.06 KB
/
index.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
import {type MutableRefObject, useState} from 'react';
import {useHookableRef} from '../useHookableRef/index.js';
import {useRafCallback} from '../useRafCallback/index.js';
import {useResizeObserver, type UseResizeObserverCallback} from '../useResizeObserver/index.js';
export type Measures = {
width: number;
height: number;
};
/**
* Uses ResizeObserver to track element dimensions and re-render component when they change.
*
* @param enabled Whether resize observer is enabled or not.
*/
export function useMeasure<T extends Element>(
enabled = true,
): [Measures | undefined, MutableRefObject<T | null>] {
const [element, setElement] = useState<T | null>(null);
const elementRef = useHookableRef<T | null>(null, (v) => {
setElement(v);
return v;
});
const [measures, setMeasures] = useState<Measures>();
const [observerHandler] = useRafCallback<UseResizeObserverCallback>((entry) => {
setMeasures({width: entry.contentRect.width, height: entry.contentRect.height});
});
useResizeObserver(element, observerHandler, enabled);
return [measures, elementRef];
}