@yamada-ui/react
Version:
React UI components of the Yamada, by the Yamada, for the Yamada built with React and Emotion
57 lines (53 loc) • 1.33 kB
JavaScript
"use client";
import { utils_exports } from "../../utils/index.js";
import { useEffect, useMemo, useRef, useState } from "react";
//#region src/hooks/use-resize-observer/index.ts
const defaultRect = {
bottom: 0,
height: 0,
left: 0,
right: 0,
top: 0,
width: 0,
x: 0,
y: 0
};
/**
* `useResizeObserver` is a custom hook that tracks changes in the size and position of an element.
*
* @see https://yamada-ui.com/docs/hooks/use-resize-observer
*/
const useResizeObserver = () => {
const id = useRef(0);
const ref = useRef(null);
const [rect, setRect] = useState(defaultRect);
const observer = useMemo(() => {
if (!(0, utils_exports.createdDom)()) return null;
return new ResizeObserver(([entry]) => {
if (!entry) return;
cancelAnimationFrame(id.current);
id.current = requestAnimationFrame(() => {
if (ref.current) setRect(entry.contentRect);
});
});
}, []);
useEffect(() => {
if (ref.current) observer?.observe(ref.current);
return () => {
observer?.disconnect();
if (id.current) cancelAnimationFrame(id.current);
};
}, [observer]);
return [ref, rect];
};
const useElementSize = () => {
const [ref, { height, width }] = useResizeObserver();
return {
ref,
height,
width
};
};
//#endregion
export { useElementSize, useResizeObserver };
//# sourceMappingURL=index.js.map