Skip to content

useMutationObserver

Subscribes to DOM mutations on a target.

Subscribes to DOM mutations on a target.

Import

import { useMutationObserver } from '@kamod-ch/hooks'

Live demo

Basic demo

Subscribes to DOM mutations on a target.

Browser-only demo

This demo starts after the page mounts in the browser.
import { useRef, useState } from 'preact/hooks'
import { useMutationObserver } from '@kamod-ch/hooks'

export default function UseMutationObserverDemo() {
  const ref = useRef<HTMLUListElement>(null)
  const [items, setItems] = useState(['first'])
  const [mutations, setMutations] = useState(0)

  useMutationObserver(() => setMutations((value) => value + 1), ref, { childList: true })

  return (
    <div>
      <ul ref={ref}>{items.map((item) => <li key={item}>{item}</li>)}</ul>
      <p><strong>Mutation callbacks:</strong> {mutations}</p>
      <button type="button" onClick={() => setItems((value) => [...value, 'item-' + (value.length + 1)])}>Append item</button>
    </div>
  )
}

API

TypeScript signature
import type { BasicTarget } from '../utils/domTarget.js';
declare const useMutationObserver: (callback: MutationCallback, target: BasicTarget, options?: MutationObserverInit) => void;
export default useMutationObserver;
/

SSR considerations

This hook touches browser APIs. Render it after mount or guard it with BrowserOnly in SSR and static builds.

Browser compatibility

Requires the corresponding browser API to exist in the current environment.