import observeRect from '@reach/observe-rect' ; import React from 'react' ; import useIsomorphicLayoutEffect from './useIsomorphicLayoutEffect' ; export type HasBoundingClientRect = { getBoundingClientRect : ( ) => DOMRect ; } ; export default function useRect ( node , enabled ) { const [ element , setElement ] = React . useState ( node ) ; let [ rect , setRect ] = React . useState < DOMRect > ( { width : 0 , height : 0 , } as DOMRect ) ; const rectRef = React . useRef ( rect ) ; rectRef . current = rect ; useIsomorphicLayoutEffect ( ( ) => { if ( node !== element ) { setElement ( node ) ; } } ) ; useIsomorphicLayoutEffect ( ( ) => { if ( enabled && element ) { setRect ( element . getBoundingClientRect ( ) ) ; } } , [ element , enabled ] ) ; React . useEffect ( ( ) => { if ( ! element || ! enabled ) { return ; } const observer = observeRect ( element as Element , ( newRect ) => { setRect ( newRect ) ; } ) ; observer . observe ( ) ; return ( ) => { observer . unobserve ( ) ; } ; } , [ element , enabled ] ) ; return rect ; }