useMutationObserver
A thin wrapper around MutationObserver. Watches a referenced element and runs a callback whenever the configured mutations fire. The observer is created on mount and disconnected automatically on cleanup.
import { useRef } from 'react'
import { useMutationObserver } from '@wire-ui/react'
function TitleWatcher() {
const ref = useRef<HTMLDivElement>(null)
useMutationObserver(
ref,
(mutations) => {
for (const m of mutations) {
if (m.type === 'attributes' && m.attributeName === 'data-state') {
console.log('state changed →', (m.target as HTMLElement).dataset.state)
}
}
},
{ attributes: true, attributeFilter: ['data-state'] },
)
return <div ref={ref} data-state="idle" />
}Parameters
| Param | Type | Description |
|---|---|---|
target | RefObject<Node | null> | The element to observe. |
callback | MutationCallback | Invoked with the list of MutationRecords. |
options | UseMutationObserverOptions | MutationObserverInit plus an enabled flag. |
Options
Accepts every key from the standard MutationObserverInit, plus:
| Option | Type | Default | Description |
|---|---|---|---|
enabled | boolean | true | Disable observation without unmounting the consumer. |
Last updated on