Skip to content

Commit

Permalink
Update useMeasure implementation
Browse files Browse the repository at this point in the history
  • Loading branch information
tylermcginnis committed Oct 9, 2023
1 parent 71c6c58 commit 5cbb6df
Showing 1 changed file with 22 additions and 18 deletions.
40 changes: 22 additions & 18 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -750,31 +750,35 @@ export function useMap(initialState) {
}

export function useMeasure() {
const ref = React.useRef(null);
const [rect, setRect] = React.useState({
const [dimensions, setDimensions] = React.useState({
width: null,
height: null,
});

React.useLayoutEffect(() => {
if (!ref.current) return;

const observer = new ResizeObserver(([entry]) => {
if (entry && entry.contentRect) {
setRect({
width: entry.contentRect.width,
height: entry.contentRect.height,
});
}
});
const previousObserver = React.useRef(null);

observer.observe(ref.current);
return () => {
observer.disconnect();
};
const customRef = React.useCallback((node) => {
if (previousObserver.current) {
previousObserver.current.disconnect();
previousObserver.current = null;
}

if (node instanceof HTMLElement) {
const observer = new ResizeObserver(([entry]) => {
if (entry && entry.borderBoxSize) {
const { inlineSize: width, blockSize: height } =
entry.borderBoxSize[0];

setDimensions({ width, height });
}
});

observer.observe(node);
previousObserver.current = observer;
}
}, []);

return [ref, rect];
return [customRef, dimensions];
}

export function useMediaQuery(query) {
Expand Down

0 comments on commit 5cbb6df

Please sign in to comment.