Skip to content

Instantly share code, notes, and snippets.

@rushkeldon
Created October 23, 2024 08:07
Show Gist options
  • Save rushkeldon/673c3e0555c17cce88f3c48fd302c982 to your computer and use it in GitHub Desktop.
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
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