typescriptadvanced
useMutationObserver Hook
Wraps the MutationObserver API in a React hook to observe DOM changes on a target element.
typescriptPress ⌘/Ctrl + Shift + C to copy
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.
typescriptintermediate
useMutation Hook for Side Effects
Handle mutations (POST/PUT/DELETE) with loading, error, reset, and optimistic update support.
Best for: Form submission handling
#react#hooks
typescriptbeginner
useEventListener Hook
Safely add and clean up DOM event listeners with a type-safe hook supporting window, document, and elements.
Best for: Window resize handling
#react#hooks
typescriptintermediate
useResizeObserver Hook
Tracks element dimensions using ResizeObserver with debounced updates.
Best for: Responsive layouts
#hooks#resize
typescriptintermediate
Infinite Scroll Hook v2
Intersection Observer-based infinite scroll with loading, error, and hasMore states.
Best for: Feed-style content
#hooks#infinite-scroll