Rooks
HooksUI & Layout

useMutationObserverRef

Returns a callback ref that observes DOM mutations on its current element.

About

useMutationObserverRef owns the ref and tracks the attached node in React state. It is the mutation-observer variant to use for conditional elements or when React may replace the observed node.

Example

import { useCallback, useState } from "react";
import { useMutationObserverRef } from "rooks";

export default function ObservedRegion() {
  const [showDetails, setShowDetails] = useState(false);
  const [mutationCount, setMutationCount] = useState(0);
  const onMutation = useCallback<MutationCallback>((records) => {
    setMutationCount((count) => count + records.length);
  }, []);
  const [regionRef] = useMutationObserverRef(onMutation);

  return (
    <section>
      <div ref={regionRef}>
        {showDetails ? <p>More details are visible.</p> : <p>Summary</p>}
      </div>
      <button type="button" onClick={() => setShowDetails((value) => !value)}>
        Toggle details
      </button>
      <p aria-live="polite">Observed mutation records: {mutationCount}</p>
    </section>
  );
}

Parameters

ParameterTypeDefaultDescription
callbackMutationCallbackrequiredReceives mutation records and the observer.
optionsMutationObserverInitall common mutation kindsPassed to observer.observe().

The default options enable attributes, characterData, childList, and subtree.

Return value

Returns [ref], a one-item tuple containing a stable callback ref for an HTMLElement.

Behavior and lifecycle

Attaching a node creates an observer; clearing, replacing, or unmounting it disconnects the previous observer. Changing the callback or options identity also disconnects and recreates it, so memoize those inputs when their behavior is unchanged.

The ref function itself stays stable. Exceptions thrown by the callback are not intercepted, and records are delivered according to the browser's normal mutation-observer microtask timing.

An options object that enables no mutation kind is invalid according to the platform and throws from observe(); the hook does not catch that error.

Compatibility and accessibility

No observer is created during server rendering or before a node attaches. Clients without MutationObserver require a polyfill or a fallback path.

Do not infer announcements, validation, or focus behavior solely from low-level mutation records. Make accessibility state explicit at the same time the application changes the UI. See SSR and browser APIs.

On this page