MCPcopy Create free account
hub / github.com/ampproject/amphtml / useMutationObserver

Function useMutationObserver

src/preact/hooks/useMutationObserver.tsx:9–28  ·  view source on GitHub ↗
(
  elementRef: RefObject<HTMLElement>,
  config: MutationObserverInit,
  onMutation: (record: MutationRecord) => void
)

Source from the content-addressed store, hash-verified

7 * Subscribes to an element's DOM mutations
8 */
9export function useMutationObserver(
10 elementRef: RefObject<HTMLElement>,
11 config: MutationObserverInit,
12 onMutation: (record: MutationRecord) => void
13) {
14 const configValues = useDeepValue(config);
15
16 const onMutationHandler = useEvent(onMutation);
17 useEffect(() => {
18 if (elementRef.current) {
19 const mo = new MutationObserver((records) => {
20 records.forEach((record) => {
21 onMutationHandler(record);
22 });
23 });
24 mo.observe(elementRef.current, configValues);
25 return () => mo.disconnect();
26 }
27 }, [configValues, /** These are stable: */ elementRef, onMutationHandler]);
28}
29
30/**
31 * Watches a DOM element's attribute for changes

Callers 1

useAttributeObserverFunction · 0.85

Calls 5

useDeepValueFunction · 0.90
useEventFunction · 0.85
forEachMethod · 0.45
observeMethod · 0.45
disconnectMethod · 0.45

Tested by

no test coverage detected