Skip to content

Instantly share code, notes, and snippets.

@Soumyarian98
Created November 5, 2024 03:16
Show Gist options
  • Select an option

  • Save Soumyarian98/8c84fe82615c38940700adaaaaaf2ef5 to your computer and use it in GitHub Desktop.

Select an option

Save Soumyarian98/8c84fe82615c38940700adaaaaaf2ef5 to your computer and use it in GitHub Desktop.
import { useEffect, useRef, useState } from "react";
const useMeasure = () => {
const ref = useRef<HTMLDivElement>(null);
const [bounds, set] = useState({ left: 0, top: 0, width: 0, height: 0 });
const [ro] = useState(
() => new ResizeObserver(([entry]) => set(entry.contentRect))
);
useEffect(() => {
if (ref.current) ro.observe(ref.current);
return () => ro.disconnect();
}, [ro]);
return [ref, bounds] as const;
};
export default useMeasure;
import { useEffect, useRef, useState } from "react";
const useMeasure = () => {
const ref = useRef<HTMLElement | null>(null);
const [bounds, setBounds] = useState<DOMRect>({
x: 0,
y: 0,
width: 0,
height: 0,
top: 0,
left: 0,
bottom: 0,
right: 0,
toJSON: () => {},
});
useEffect(() => {
if (!ref.current) return;
let animationFrameId: number;
const observer = new ResizeObserver(([entry]) => {
// Use `requestAnimationFrame` to prevent layout thrashing
animationFrameId = requestAnimationFrame(() => {
if (entry) setBounds(entry.contentRect);
});
});
observer.observe(ref.current);
return () => {
cancelAnimationFrame(animationFrameId);
observer.disconnect();
};
}, []);
return [ref, bounds] as const;
};
export default useMeasure;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment