UseMutationObserver
guarahooks/use-mutation-observerFreeHook
Observes changes to the DOM using the Mutation Observer API
Live preview
live · rendered by the registry
Rendered by guarahooks on their own page — this is the component running, not a screenshot of it.Install it
npx shadcn@latest add https://guarahooks.com/r/use-mutation-observer.jsonSource
1'use client';23import { useCallback, useEffect, useRef } from 'react';45// Types6type UseMutationObserverProps<T extends HTMLElement = HTMLElement> = {7 target: React.RefObject<T | null>;8 options?: MutationObserverInit;9 callback: MutationCallback;10};1112export function useMutationObserver<T extends HTMLElement = HTMLElement>({13 target,14 options = {15 attributes: true,16 childList: true,17 subtree: true,18 },19 callback,20}: UseMutationObserverProps<T>) {21 const observerRef = useRef<MutationObserver | null>(null);22 const prevTargetRef = useRef<T | null>(null);2324 const disconnect = useCallback(() => {25 if (observerRef.current) {26 observerRef.current.disconnect();27 observerRef.current = null;28 }29 }, []);3031 useEffect(() => {32 const node = target.current;33 if (!node) return;3435 if (prevTargetRef.current !== node) {36 disconnect();37 prevTargetRef.current = node;38 }3940 observerRef.current = new MutationObserver(callback);41 observerRef.current.observe(node, options);42 return () => {43 disconnect();44 };45 }, [target, options, callback, disconnect]);4647 return {48 disconnect,49 };50}
Files it writes
More from guarahooks
All 100 items| Component | Registry | Kind | Access | Installs | Command |
|---|---|---|---|---|---|
| UseAbortControlleruse-abort-controller | guarahooks | Hooks | Free | no deps | |
| UseArrayStateuse-array-state | guarahooks | Hooks | Free | no deps | |
| UseAxiosuse-axios | guarahooks | Hooks | Free | no deps | |
| UseBatteryStatususe-battery-status | guarahooks | Hooks | Free | no deps | |
| UseBetterAuthuse-better-auth | guarahooks | Hooks | Free | no deps | |
| UseClickOutsideuse-click-outside | guarahooks | Hooks | Free | no deps | |
| UseConfirmuse-confirm | guarahooks | Hooks | Free | no deps | |
| UseCookieuse-cookie | guarahooks | Hooks | Free | no deps |
