Docs
useMutationObserver
Observe mutations on a DOM element with the useMutationObserver hook.
Installation
pnpm dlx shadcn@latest add https://usekit.kiron.dev/k/use-mutation-observer
Usage
"use client"
import * as React from "react"
import { useMutationObserver } from "@/hooks/use-mutation-observer"
export function Component() {
const ref = React.useRef<HTMLDivElement>(null)
const callback: MutationCallback = (mutationsList) => {
for (const mutation of mutationsList) {
if (mutation.type === "attributes") {
console.log("Attribute changed:", mutation.attributeName)
} else if (mutation.type === "childList") {
console.log("Child nodes changed")
} else if (mutation.type === "characterData") {
console.log("Text content changed")
}
}
}
useMutationObserver(ref, callback)
return (
<div ref={ref}>
<p>Observe changes in this element</p>
</div>
)
}
API Reference
Parameters
Name | Type | Description | Default Value | Optional |
---|---|---|---|---|
ref | React.MutableRefObject<HTMLElement | null> | A ref to the DOM element to observe. | - | No |
callback | MutationCallback | A callback function that will be called when mutations are observed. | - | No |
options | MutationObserverInit | Options for the MutationObserver (e.g., attributes , childList , etc.). | { attributes: true, characterData: true, childList: true, subtree: true } | Yes |