Skip to content

Instantly share code, notes, and snippets.

@samuelkarani
Created August 5, 2023 10:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save samuelkarani/bcf83d4d7d7903f034c7a61f55060d1b to your computer and use it in GitHub Desktop.
Save samuelkarani/bcf83d4d7d7903f034c7a61f55060d1b to your computer and use it in GitHub Desktop.
export function useBoundingClientRect<T extends HTMLElement>() {
const [rect, setRect] = useState<DOMRect | null>(null);
const ref = useRef<T>(null);
const update = useCallback(() => {
if (ref.current) setRect(ref.current.getBoundingClientRect());
else setRect(null);
}, []);
useEffectOnce(() => {
setTimeout(update, 500);
});
useEventListener("resize", update);
return [ref, rect] as const;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment