2021-09-30 07:29:25 -04:00
|
|
|
import { useCallback, useEffect, useRef } from 'react'
|
|
|
|
|
2023-02-06 09:17:22 -05:00
|
|
|
export const useResizeObserver = (handleResize: (element: Element) => void) => {
|
|
|
|
const resizeRef = useRef<{
|
|
|
|
element: Element
|
|
|
|
observer: ResizeObserver
|
|
|
|
} | null>(null)
|
2021-09-30 07:29:25 -04:00
|
|
|
|
|
|
|
const elementRef = useCallback(
|
2023-02-06 09:17:22 -05:00
|
|
|
(element: Element | null) => {
|
2021-11-29 06:59:34 -05:00
|
|
|
if (element && 'ResizeObserver' in window) {
|
2021-09-30 07:29:25 -04:00
|
|
|
if (resizeRef.current) {
|
|
|
|
resizeRef.current.observer.unobserve(resizeRef.current.element)
|
|
|
|
}
|
|
|
|
|
|
|
|
const observer = new ResizeObserver(([entry]) => {
|
2021-10-15 06:42:47 -04:00
|
|
|
handleResize(entry.target)
|
2021-09-30 07:29:25 -04:00
|
|
|
})
|
|
|
|
|
|
|
|
resizeRef.current = { element, observer }
|
|
|
|
|
|
|
|
observer.observe(element)
|
2021-10-15 06:42:47 -04:00
|
|
|
|
|
|
|
handleResize(element) // trigger the callback once
|
2021-09-30 07:29:25 -04:00
|
|
|
}
|
|
|
|
},
|
2021-10-15 06:42:47 -04:00
|
|
|
[handleResize]
|
2021-09-30 07:29:25 -04:00
|
|
|
)
|
|
|
|
|
|
|
|
useEffect(() => {
|
|
|
|
return () => {
|
|
|
|
if (resizeRef.current) {
|
|
|
|
resizeRef.current.observer.unobserve(resizeRef.current.element)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}, [])
|
|
|
|
|
2023-07-18 06:21:56 -04:00
|
|
|
return { elementRef, resizeRef }
|
2021-09-30 07:29:25 -04:00
|
|
|
}
|