Skip to Content
ohooks

useMutationObserver

Observes DOM tree, attribute, or character data mutations on a target node using MutationObserver.

Loading preview...

The useMutationObserver hook attaches a MutationObserver to a target DOM node and invokes a callback whenever matching attribute, child list, or character data mutations occur.

Installation

pnpm dlx shadcn@latest add https://ohooks.vercel.app/r/useMutationObserver.json

Usage

Examples

Watching data-* or aria-* Attribute Changes

Configure attributes: true and attributeFilter to react only when specific attributes change on a target element.

Pausing Observation with enabled

Set enabled: false in the options object to temporarily disconnect the MutationObserver.

API Reference

UseMutationObserverOptions

Configuration options extending standard MutationObserverInit with an enabled flag.

Property
Specification
enabled?
uniondefault:true
Whether the mutation observer is active
attributeFilter?
array
Set to a list of attribute local names (without namespace) if not all attribute mutations need to be observed and attributes is true or omitted.
attributeOldValue?
union
Set to true if attributes is true or omitted and target's attribute value before the mutation needs to be recorded.
attributes?
union
Set to true if mutations to target's attributes are to be observed. Can be omitted if attributeOldValue or attributeFilter is specified.
characterData?
union
Set to true if mutations to target's data are to be observed. Can be omitted if characterDataOldValue is specified.
characterDataOldValue?
union
Set to true if characterData is set to true or omitted and target's data before the mutation needs to be recorded.
childList?
union
Set to true if mutations to target's children are to be observed.
subtree?
union
Set to true if mutations to not just target, but also target's descendants are to be observed.