MutationObserver Guide: Detect DOM Changes in JS & React

A third-party script injects a widget into your page, and you need to run code the moment it appears. You don't control that script, so there is no callback to hook into. The usual answer is a setInterval that checks for the element every 100 milliseconds. It works, but it wastes work on every tick, it fires late, and nobody ever removes it.

The MutationObserver API solves this properly. You tell the browser which part of the DOM to watch and what kind of change you care about, and it calls your function when that change happens. No polling, no guessing, and no deprecated events.

This MutationObserver guide explains how the API works, which options matter, and where it surprises people. It then builds practical tools in vanilla JavaScript (a waitForElement helper, an attribute watcher, a handler for dynamically added elements) and shows how to use MutationObserver in React safely, with a reusable hook, a useSyncExternalStore variant, and tests.

It is the third member of an observer family we have covered. ResizeObserver reports size changes, and IntersectionObserver reports visibility changes. MutationObserver reports changes to the DOM itself.

What MutationObserver Does (and What It Doesn't)