feat(utils): add hooks for dom observer

This commit is contained in:
unix
2020-05-24 01:49:46 +08:00
parent 212d2e3eab
commit fb6be97d79

View File

@@ -0,0 +1,25 @@
import { MutableRefObject, useEffect } from 'react'
const useDOMObserver = (
ref: MutableRefObject<HTMLElement | null> | undefined,
callback: MutationCallback = () => {},
) => {
const config = { attributes: false, childList: true, subtree: true }
useEffect(() => {
if (!ref || !ref.current) return
let unmount = false
const done: MutationCallback = (...params) => {
if (unmount) return
callback(...params)
}
const observer = new MutationObserver(done)
observer.observe(ref.current, config)
return () => {
unmount = true
observer.disconnect()
}
}, [ref])
}
export default useDOMObserver