@ducor/hooks
Version:
A collection of useful React hooks for building modern web applications. Includes hooks for clipboard operations, window events, intervals, timeouts, and more.
46 lines (45 loc) • 1.47 kB
JavaScript
import { useEffect, useMemo, useRef, useState } from 'react';
const defaultState = {
x: 0,
y: 0,
width: 0,
height: 0,
top: 0,
left: 0,
bottom: 0,
right: 0,
};
export function useResizeObserver(elementRef, options) {
const frameID = useRef(0);
const ref = elementRef ? elementRef : useRef(null);
const [rect, setRect] = useState(defaultState);
const observer = useMemo(() => typeof window !== 'undefined'
? new ResizeObserver((entries) => {
const entry = entries[0];
if (entry) {
cancelAnimationFrame(frameID.current);
frameID.current = requestAnimationFrame(() => {
if (ref.current) {
setRect(entry.contentRect);
}
});
}
})
: null, []);
useEffect(() => {
if (ref.current) {
observer === null || observer === void 0 ? void 0 : observer.observe(ref.current, options);
}
return () => {
observer === null || observer === void 0 ? void 0 : observer.disconnect();
if (frameID.current) {
cancelAnimationFrame(frameID.current);
}
};
}, [ref.current]);
return [ref, rect];
}
export default function useElementSize(elementRef, options) {
const [ref, { width, height }] = useResizeObserver(elementRef, options);
return { ref, width, height };
}