mirror of
https://github.com/zhigang1992/react.git
synced 2026-02-07 22:41:59 +08:00
26 lines
655 B
TypeScript
26 lines
655 B
TypeScript
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
|