preact-missing-hooks
Version:
A lightweight, extendable collection of missing React-like hooks for Preact — plus fresh, powerful new ones designed specifically for modern Preact apps.
27 lines (22 loc) • 755 B
text/typescript
import { RefObject } from "preact";
import { useEffect } from "preact/hooks";
export type UseMutationObserverOptions = MutationObserverInit;
/**
* A Preact hook to observe DOM mutations using MutationObserver.
* @param target - The element to observe.
* @param callback - Function to call on mutation.
* @param options - MutationObserver options.
*/
export function useMutationObserver(
targetRef: RefObject<HTMLElement | null>,
callback: MutationCallback,
options: MutationObserverInit
) {
useEffect(() => {
const node = targetRef.current;
if (!node) return;
const observer = new MutationObserver(callback);
observer.observe(node, options);
return () => observer.disconnect();
}, [targetRef, callback, options]);
}