useMutationObserver
Creates and manages a browser MutationObserver for one or more target elements. The observer is built once the targets resolve and is released when the owning scope stops.
Exports
function useMutationObserver(
target: TargetRef,
callback: (items: Array<{ entry: MutationRecord; target: HTMLElement }>) => void,
options?: MaybeRefOrGetter<MutationObserverInit>,
): ObserverResults<MutationObserver>Types
type TargetRef =
| MaybeRefOrGetter<Nullable<HTMLElement>>
| MaybeRefOrGetter<Nullable<HTMLElement>>[]
| MaybeRefOrGetter<Nullable<HTMLElement>[]>
interface ObserverResults<TObserver> {
observer: Ref<TObserver | undefined>
stop: () => void
}Params
| Name | Type | Description |
|---|---|---|
target | TargetRef | The target element(s) to observe. Duplicates are collapsed. |
callback | (items: Array<{ entry: MutationRecord; target: HTMLElement }>) => void | Fired with the entries reported since the last callback. Each item carries the registered element it belongs to. |
options | MaybeRefOrGetter<MutationObserverInit> | Observer configuration. May be a getter, in which case changing its result rebuilds the observer. |
Notes
- Instances are not shared. A
subtreeobserver reports descendants, so each record has to be attributed back to the registered element, which is not worth doing safely across many subscribers. - An item’s
entryis aMutationRecord: its owntargetis the changed node, while the item’stargetis the element that was registered. - The native
observerequires at least one ofattributes,characterDataorchildListto betrue, sooptionshas to set one. optionsare compared after normalisation, so equivalent values such asthreshold: [0, 1]andthreshold: [1, 0]reuse the same observer.- Changing
targetadds or removes elements without recreating the observer; only anoptionschange rebuilds it. stop()releases the observer immediately. Inside a component that is optional, because scope disposal does the same thing.