Skip to content

Commit 5cbb6df

Browse files
committed
Update useMeasure implementation
1 parent 71c6c58 commit 5cbb6df

File tree

1 file changed

+22
-18
lines changed

1 file changed

+22
-18
lines changed

index.js

Lines changed: 22 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -750,31 +750,35 @@ export function useMap(initialState) {
750750
}
751751

752752
export function useMeasure() {
753-
const ref = React.useRef(null);
754-
const [rect, setRect] = React.useState({
753+
const [dimensions, setDimensions] = React.useState({
755754
width: null,
756755
height: null,
757756
});
758757

759-
React.useLayoutEffect(() => {
760-
if (!ref.current) return;
761-
762-
const observer = new ResizeObserver(([entry]) => {
763-
if (entry && entry.contentRect) {
764-
setRect({
765-
width: entry.contentRect.width,
766-
height: entry.contentRect.height,
767-
});
768-
}
769-
});
758+
const previousObserver = React.useRef(null);
770759

771-
observer.observe(ref.current);
772-
return () => {
773-
observer.disconnect();
774-
};
760+
const customRef = React.useCallback((node) => {
761+
if (previousObserver.current) {
762+
previousObserver.current.disconnect();
763+
previousObserver.current = null;
764+
}
765+
766+
if (node instanceof HTMLElement) {
767+
const observer = new ResizeObserver(([entry]) => {
768+
if (entry && entry.borderBoxSize) {
769+
const { inlineSize: width, blockSize: height } =
770+
entry.borderBoxSize[0];
771+
772+
setDimensions({ width, height });
773+
}
774+
});
775+
776+
observer.observe(node);
777+
previousObserver.current = observer;
778+
}
775779
}, []);
776780

777-
return [ref, rect];
781+
return [customRef, dimensions];
778782
}
779783

780784
export function useMediaQuery(query) {

0 commit comments

Comments
 (0)