overleaf/services/web/frontend/js/shared/hooks/use-resize-observer.js
Timothée Alby aef02eb0a4 Merge pull request #3494 from overleaf/ae-eslint-hooks
Re-enable react-hooks/exhaustive-deps

GitOrigin-RevId: 2a767596d2cfd41b8bfbd3928dc43c266ec7dc0c
2021-01-08 03:05:08 +00:00

36 lines
974 B
JavaScript

import { useLayoutEffect, useRef, useCallback } from 'react'
function useResizeObserver(observedElement, observedData, callback) {
const resizeObserver = useRef()
const observe = useCallback(() => {
resizeObserver.current = new ResizeObserver(function(elementsObserved) {
callback(elementsObserved[0])
})
}, [callback])
function unobserve(observedCurrent) {
resizeObserver.current.unobserve(observedCurrent)
}
useLayoutEffect(() => {
if ('ResizeObserver' in window) {
const observedCurrent = observedElement && observedElement.current
if (observedCurrent) {
observe(observedElement.current)
}
if (resizeObserver.current && observedCurrent) {
resizeObserver.current.observe(observedCurrent)
}
return () => {
if (observedCurrent) {
unobserve(observedCurrent)
}
}
}
}, [observedElement, observedData, observe])
}
export default useResizeObserver