typescriptadvanced

useMutationObserver Hook

Wraps the MutationObserver API in a React hook to observe DOM changes on a target element.

typescript
import { useEffect, useRef, RefObject } from 'react';

export function useMutationObserver<T extends HTMLElement>(
  callback: MutationCallback,
  options: MutationObserverInit = { childList: true, subtree: true }
): RefObject<T | null> {
  const ref = useRef<T | null>(null);
  const callbackRef = useRef(callback);

  useEffect(() => {
    callbackRef.current = callback;
  }, [callback]);

  useEffect(() => {
    const node = ref.current;
    if (!node) return;

    const observer = new MutationObserver((...args) => callbackRef.current(...args));
    observer.observe(node, options);
    return () => observer.disconnect();
  }, [options.childList, options.subtree, options.attributes]);

  return ref;
}

Use Cases

  • Third-party widget monitoring
  • Dynamic content tracking

Tags

Related Snippets

Similar patterns you can reuse in the same workflow.