Raw
1 "use client"
2
3 import { useEffect } from "react"
4
5 type UseMutationObserverProps = {
6 elm: Document | HTMLElement | undefined
7 callback: () => void
8 options?: {
9 attributes?: boolean
10 characterData?: boolean
11 childList?: boolean
12 subtree?: boolean
13 }
14 }
15
16 export const useMutationObserver = ({
17 elm,
18 callback,
19 options = {
20 attributes: true,
21 characterData: true,
22 childList: true,
23 subtree: true,
24 },
25 }: UseMutationObserverProps) => {
26 useEffect(() => {
27 if (elm) {
28 const observer = new MutationObserver(callback)
29 observer.observe(elm, options)
30 return () => observer.disconnect()
31 }
32 }, [callback, options])
33 }