useMutationObserver
Registers a MutationObserver on ref and executes callback when the
observed element is mutated.
- @param
ref- ARefObjectof the element to observe. - @param
callback- A function to execute when the observed element is mutated. - @param
options- Configurable options - @param
options.when- Whether observation is enabled. - @param
options.attributeFilter- Attribute names to observe. - @param
options.attributeOldValue- Whether to record previous attribute values. - @param
options.attributes- Whether to observe attribute changes. - @param
options.characterData- Whether to observe character-data changes. - @param
options.characterDataOldValue- Whether to record previous character data. - @param
options.childList- Whether to observe child-list changes. - @param
options.subtree- Whether to observe all descendants. - @returns void
Example
const ref = useRef<HTMLDivElement>(null);
const [isLoading, setIsLoading] = useState(false);
useMutationObserver(ref, (record) => {
setIsLoading(record.attributeName);
}, { attributes: true, attributeFilter: ['data-loading'] });