Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

REACT- DOM Mutation Warning Meaning

[Violation] Added synchronous DOM mutation listener to a 'DOMNodeInserted' event. Consider using MutationObserver to make the page more responsive.

There's another question regarding this warning. I already answered a way to solve it there, and that is not the reason for this question. (for those who would like to know: this warning disappears if you add a setTimeOut function to your event handler, so it is not synchronous anymore)

The REAL question is: What does "DOM mutation listener" mean? Or what IS a "DOM mutation listener"? And what does it do? I asked my teacher, and not even him knew. He suggested it might be something now deprecated but I feel like it shows up for a reason and I would like to fully understand it in case i get a similar error but different regarding a "DOM mutation listener" in the future.

like image 653
GiselleMtnezS Avatar asked Oct 29 '25 08:10

GiselleMtnezS


1 Answers

A DOM mutation listener does just what it sounds like - it listens for mutations to the DOM. For example, if you attach such a listener, and then add or remove a node, the listener may be able to detect it and fire a callback. There are various types of DOM mutations that can be watched for.

For an example of a synchronous one (which are slow, deprecated, and not recommended):

container.addEventListener('DOMNodeInserted', () => {
  console.log('mutation seen!');
});

container.insertAdjacentHTML('beforeend', 'content');
<div id="container"></div>

For this sort of functionality, you're recommended to use MutationObserver instead, which is not quite synchronous - a MutationObserver callback runs during a microtask after the mutation:

new MutationObserver(() => {
  console.log('mutation seen!');
}).observe(container, { childList: true });

container.insertAdjacentHTML('beforeend', 'content');
<div id="container"></div>

Mutation observers are usually only the right choice when you need to interact with the functionality of code you can't change - for example, if you're using a script or a library that changes something in the DOM, and you need to be able to detect when that change occurs, but you can't modify the source script and that script doesn't provide any externally-visible indication that such a change occurred.

Except in that (unusual) situation, there are usually better methods to react to changes, such as just calling a function after the function that changes the DOM is done.

like image 69
CertainPerformance Avatar answered Oct 31 '25 00:10

CertainPerformance



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!