Skip to main content

useMutationObserver

Purpose

The useMutationObserver hook allows you to observe changes to the DOM. It is a wrapper around the MutationObserver API, making it easier to use in Stimulus components and automating registering and cleaning up the observer on connect and disconnect.

Side Effects

The useMutationObserver hook will create an instance of MutationObserver when it is called. It will also register the observer with the DOM. When the component is unmounted, the observer will be disconnected.

Usage

useMutationObserver

ParametersTypePurposeDefault
controllerControllerThe instance of the controller to install the behaviour on. This allows the mixin to automatically register cleanup on the controller's disconnect.this
elementHTMLElementThe element to observe.
handler (Optional)FunctionThe callback to invoke when the changes occur. Accepts a single parameter which is an array of MutationRecord Reference.
options (Optional)MutationObserverInit ReferenceThe raw options to pass to to the observe call when initializing the MutationObserver