-
-
Save AndriiTsok/342ceccff959c6180f6a79cbe01e5a71 to your computer and use it in GitHub Desktop.
A generic React TypeScript hook for measuring element dimensions in real-time
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment