Skip to content

Commit

Permalink
Change hook to not need polling
Browse files Browse the repository at this point in the history
  • Loading branch information
Your Name committed Aug 30, 2024
1 parent 5f0240a commit 874d4b2
Showing 1 changed file with 11 additions and 16 deletions.
27 changes: 11 additions & 16 deletions packages/components/src/lib/hooks/useInitialNonzeroWidth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,26 +8,21 @@ export function useInitialNonzeroWidth() {
const [width, setWidth] = useState<number | undefined>();

useEffect(() => {
const updateWidth = () => {
if (ref.current) {
const currentWidth = ref.current.offsetWidth;
if (currentWidth > 0) {
setWidth(currentWidth);
return true;
}
if (!ref.current) return;

const updateWidth = (entries: ResizeObserverEntry[]) => {
const entry = entries[0];
if (entry && entry.contentRect.width > 0) {
setWidth(entry.contentRect.width);
}
return false;
};

if (!updateWidth()) {
const intervalId = setInterval(() => {
if (updateWidth()) {
clearInterval(intervalId);
}
}, 100);
const resizeObserver = new ResizeObserver(updateWidth);
resizeObserver.observe(ref.current);

return () => clearInterval(intervalId);
}
return () => {
resizeObserver.disconnect();
};
}, []);

return { ref, width };
Expand Down

0 comments on commit 874d4b2

Please sign in to comment.