Created
October 23, 2024 08:07
-
-
Save rushkeldon/673c3e0555c17cce88f3c48fd302c982 to your computer and use it in GitHub Desktop.
useElementRect - a react hook that keeps the current rectangle inhabited by an element up-to-date
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 { RefObject, useEffect, useState, useRef } from 'react'; | |
const useElementRect = <T extends HTMLElement>(): [RefObject<T>, DOMRect] => { | |
const [rect, setRect] = useState<DOMRect>(new DOMRect()); | |
const ref = useRef<T>(null); | |
useEffect(() => { | |
const updateRect = () => setRect(ref?.current?.getBoundingClientRect() || new DOMRect()); | |
updateRect(); | |
const observer = new ResizeObserver(updateRect); | |
ref.current && observer.observe(ref.current); | |
return () => observer.disconnect(); | |
}, []); | |
return [ref, rect]; | |
}; | |
export default useElementRect; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment