| 1 | import { useLayoutEffect, useCallback, useState } from 'react'; |
| 2 | |
| 3 | export const useRect = (ref) => { |
| 4 | |
| 5 | const [rect, setRect] = useState({ width: 0, height: 0, top: 0, left: 0, right: 0, bottom: 0 }); |
| 6 | |
| 7 | const updateRect = useCallback(() => { |
| 8 | if (ref.current) { |
| 9 | setRect(ref.current.getBoundingClientRect()); |
| 10 | } |
| 11 | }, [ref]); |
| 12 | |
| 13 | useLayoutEffect(() => { |
| 14 | if (!ref.current) return; |
| 15 | |
| 16 | const timeout = setTimeout(updateRect, 0); // Delay to next event loop |
| 17 | |
| 18 | const observer = new ResizeObserver(updateRect); |
| 19 | observer.observe(ref.current); |
| 20 | |
| 21 | return () => { |
| 22 | observer.disconnect() |
| 23 | clearTimeout(timeout) |
| 24 | } |
| 25 | }, [updateRect, ref]); |
| 26 | |
| 27 | return rect; |
| 28 | }; |
| 29 | |
| 30 | /** |
| 31 | * Higher order component to make use of the useRect |