Founding price: $35, then $99 after 23:59 UTC on 4 November, then $99
Get ProRun a callback when an element's attributes, children or text change, with the observed node given as a ref, an element or a selector.
This item has no props to tune. Use the lens above to change theme, density, direction and more.
Use it to react to changes you do not own: a class added by a third-party script, children inserted into a container, an attribute flipped by a widget.
Do not use it to watch your own React state; that is what state and effects are for.
import { useMutationObserver } from "@/hooks/use-mutation-observer"useMutationObserver(
ref,
(records) => setCount(ref.current?.children.length ?? 0),
{ childList: true }
)useMutationObserver(target, callback, options?): void
| Name | Type | Description |
|---|---|---|
target | RefObject<Node | null> | Node | null | What to observe. A ref is read when the effect runs. |
callback | (records: MutationRecord[]) => void | Called with the records. The newest version is used. |
options | MutationObserverInit | Default { attributes: true, childList: true, subtree: true }. |
The observer is recreated when the target or options change and disconnected on unmount.
A hook has no markup. If a mutation changes what people can perceive, make sure the code that causes it also updates ARIA state or live regions; do not use the observer to patch accessibility after the fact.
The hook ships with renderHook tests (use-mutation-observer.test.ts) covering its behaviour, cleanup on unmount and server-safe defaults. It is safe to render on the server.