npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@usefy/use-mutation-observer

v0.25.1

Published

A React hook for observing DOM mutations using the MutationObserver API

Readme


Overview

useMutationObserver is part of the @usefy ecosystem — a collection of production-ready, TypeScript-first, SSR-safe React hooks. It wraps the browser's MutationObserver API so you can react to DOM mutations — child nodes added/removed, attributes changing, or character data changing — by attaching a single callback ref.

It is the low-level observer primitive, a sibling to @usefy/use-resize-observer and @usefy/use-intersection-observer, and follows the same ref / enabled / onXxx / updateState conventions.

Features

  • Callback ref — attach ref to a node to observe it; pass null to disconnect
  • Full MutationObserverInit surfacechildList, attributes, attributeFilter, attributeOldValue, characterData, characterDataOldValue, subtree
  • Sensible default — defaults to childList: true (and implies attributes/characterData from their sub-options) so observe() never throws
  • Callback + state — react via onMutation, or the reactive records state, or both; updateState: false for zero-re-render callback-only mode
  • Stable callbackonMutation is stored in a ref, so changing its identity every render does not tear down and re-create the observer
  • enabled toggle & manual controls — pause observation, or drive observe / disconnect / takeRecords yourself
  • SSR-safe — no MutationObserver/DOM access on the server; degrades to isSupported: false
  • StrictMode / concurrent-safe — clean connect/disconnect with no leaked observers
  • TypeScript-first — full type inference and exported types
  • Tiny & tree-shakeable — zero dependencies, published as its own package

Installation

# npm
npm install @usefy/use-mutation-observer

# yarn
yarn add @usefy/use-mutation-observer

# pnpm
pnpm add @usefy/use-mutation-observer

Requires React 18 or 19 (peerDependencies: "react": "^18.0.0 || ^19.0.0").

Quick Start

import { useMutationObserver } from "@usefy/use-mutation-observer";

function Watched() {
  const { ref, records } = useMutationObserver<HTMLDivElement>({
    childList: true,
    subtree: true,
    onMutation: (mutations) => {
      for (const m of mutations) console.log(m.type, m.target);
    },
  });

  return <div ref={ref}>{records.length} recent mutations</div>;
}

API

useMutationObserver<T>(options?)

Observes the element attached via the returned ref for DOM mutations.

Options — UseMutationObserverOptions<T>

| Option | Type | Default | Description | | ----------------------- | ---------------------------------------------------------- | -------- | ------------------------------------------------------------------------------------------- | | childList | boolean | true* | Observe additions/removals of the target's child nodes | | attributes | boolean | false | Observe attribute changes (implied true when attributeFilter/attributeOldValue is set)| | attributeFilter | string[] | — | Only observe the named attributes (implies attributes: true) | | attributeOldValue | boolean | false | Record the previous attribute value in MutationRecord.oldValue (implies attributes) | | characterData | boolean | false | Observe character-data changes | | characterDataOldValue | boolean | false | Record the previous character data in oldValue (implies characterData) | | subtree | boolean | false | Extend observation to the whole subtree, not just direct children | | onMutation | (mutations: MutationRecord[], observer: MutationObserver) => void | — | Callback fired with each batch of records (stored in a ref — safe to pass inline) | | enabled | boolean | true | When false, disconnects and stops reporting; flip back to true to re-observe | | updateState | boolean | true | Whether to mirror the latest batch into the records state. false = callback-only |

* childList defaults to true only when none of childList/attributes/characterData is enabled — the DOM API requires at least one.

Returns — UseMutationObserverReturn<T>

| Property | Type | Description | | ------------- | --------------------------------- | ----------------------------------------------------------------------- | | ref | (element: T \| null) => void | Callback ref to attach to the target; null disconnects | | records | readonly MutationRecord[] | The latest batch of records (empty until the first mutation) | | isSupported | boolean | Whether the MutationObserver API is available | | isObserving | boolean | Whether the hook is currently observing an element | | observe | (element: T) => void | Manually start observing an element (escape hatch alongside ref) | | disconnect | () => void | Disconnect the observer, stopping all observation | | takeRecords | () => MutationRecord[] | Flush and return any queued-but-undelivered records |

Note: MutationObserver has no per-target unobserve; disconnect() (dropping all observation) is the only way to stop, matching the native API.

disconnect() is terminal: after calling it, re-attaching the same ref does not restart observation (the ref only re-observes when the element changes, and the internal observer is torn down). To resume, call observe(element) again, or remount the component.

Also exported: isMutationObserverSupported() and resolveMutationConfig(options) (pure helpers), the EMPTY_RECORDS sentinel, and the UseMutationObserverOptions, UseMutationObserverReturn, OnMutationCallback types.

Examples

Callback-only mode (zero re-renders)

import { useMutationObserver } from "@usefy/use-mutation-observer";

function ClassWatcher() {
  const { ref } = useMutationObserver({
    attributeFilter: ["class"],
    attributeOldValue: true,
    updateState: false, // skip state, handle everything in the callback
    onMutation: (mutations) => {
      const last = mutations[mutations.length - 1];
      console.log(last?.attributeName, "was", last?.oldValue);
    },
  });

  return <div ref={ref} className="box" />;
}

Pause and resume observation

import { useState } from "react";
import { useMutationObserver } from "@usefy/use-mutation-observer";

function Toggleable() {
  const [enabled, setEnabled] = useState(true);
  const { ref, records } = useMutationObserver({ childList: true, enabled });

  return (
    <div>
      <button onClick={() => setEnabled((e) => !e)}>
        {enabled ? "Pause" : "Resume"} observing
      </button>
      <div ref={ref}>{records.length} recent child mutations</div>
    </div>
  );
}

Testing

📊 View Detailed Coverage Report (GitHub Pages) — 62 tests, 99% statement coverage.

  • useMutationObserver.test.ts — 44 tests for hook behavior (observation, options passthrough, callback-ref, enabled, stable callback, manual control, cleanup, StrictMode, unsupported env)
  • utils.test.ts — 18 tests for the config resolver and helpers

License

MIT © mirunamu

This package is part of the usefy monorepo.