Skip to content

Instantly share code, notes, and snippets.

@KristofferEriksson
Created January 27, 2024 16:52
Show Gist options
  • Save KristofferEriksson/2672c3d20afea9e37c75265d0318d804 to your computer and use it in GitHub Desktop.
Save KristofferEriksson/2672c3d20afea9e37c75265d0318d804 to your computer and use it in GitHub Desktop.
A generic React TypeScript hook for measuring element dimensions in real-time
import { useEffect, useRef, useState } from "react";
interface MeasureResult<T extends Element> {
ref: React.RefObject<T>;
bounds: DOMRectReadOnly;
}
const useMeasure = <T extends Element = Element>(): MeasureResult<T> => {
const ref = useRef<T>(null);
const [bounds, setBounds] = useState<DOMRectReadOnly>(new DOMRectReadOnly());
useEffect(() => {
let observer: ResizeObserver;
if (ref.current) {
observer = new ResizeObserver(([entry]) => {
if (entry) {
setBounds(entry.contentRect);
}
});
observer.observe(ref.current);
}
return () => {
if (observer) {
observer.disconnect();
}
};
}, []);
return { ref, bounds };
};
export default useMeasure;
@devsmartproject
Copy link

Good!

@KristofferEriksson
Copy link
Author

Good!

Thank you @devsmartproject!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment