Skip to content

Commit

Permalink
🪝 [useElementRect] New element measurement hook
Browse files Browse the repository at this point in the history
  • Loading branch information
beefchimi committed Apr 13, 2024
1 parent a531604 commit 496a343
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/hooks/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
export * from './useResizeObserver';

export {useElementRect} from './useElementRect';
export {useIsoEffect} from './useIsoEffect';
export {useMounted} from './useMounted';

Expand Down
52 changes: 52 additions & 0 deletions src/hooks/useElementRect.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import {useCallback, useRef, useState} from 'react';

import {useIsoEffect} from './useIsoEffect';
import {useResizeObserver} from './useResizeObserver';
import {useWindowScroll} from './useWindowScroll';

interface RectSubset {
top: number;
right: number;
bottom: number;
left: number;
width: number;
height: number;
}

const INITIAL_RECT: RectSubset = {
top: 0,
right: 0,
bottom: 0,
left: 0,
width: 0,
height: 0,
};

// TODO: Do we want to create and provide the `ref`,
// or accept it as an option?
export function useElementRect() {
const ref = useRef<HTMLElement>(null);
const [rect, setRect] = useState<RectSubset>(INITIAL_RECT);

const updateRect = useCallback(() => {
if (ref.current) {
setRect(ref.current.getBoundingClientRect());
}
}, []);

const {scrollX, scrollY, visibleWidth, visibleHeight} = useWindowScroll({
updateStrategy: 'aggressive',
});

useResizeObserver({ref, onResize: updateRect});

useIsoEffect(() => {
updateRect();
}, [scrollX, scrollY, visibleWidth, visibleHeight]);

return {
ref,
rect,
updateRect,
};
}

0 comments on commit 496a343

Please sign in to comment.