DOM reconciliation

To illustrate this challenge, consider a simple shopping list in the form of an array composed of individual items as strings:

const shoppingList = ['Bananas', 'Apples', 'Chocolate'];

Deriving a DOM tree from this data is quite simple:

const ul = document.createElement('ul');
shoppingList.forEach(item => {
const li = ul.appendChild(document.createElement('li'));
li.textContent = item;
});
document.body.appendChild(ul);

This code would produce the following DOM tree (and append it to <body>):

<ul>
<li>Bananas</li>
<li>Apples</li>
<li>Chocolate</li>
</ul>

But what happens if our data changes? And what would happen if there were <input> via which users could add new items? To accommodate these things, we would have to implement an abstraction to hold our data and raise events (or invoke callbacks) whenever the data changes. Additionally, we'd need some way of tying each individual data item to a DOM node. If the first item, "Bananas" were to be changed to "Melons", then we should only make the minimum mutations necessary to the DOM to reflect that change. In this case, we would want to replace the first <li> element's inner text node's data property (in other words, the actual text contained within the text node):

shoppingList[0] = 'Melons';
ul.children[0].firstChild.data = shoppingList[0];

This type of change, in abstract terms, is known as DOM reconciliation and involves reflecting any changes made to data within the DOM. There are broadly three types of reconciliation:

  • Update: If an existing data item is updated, then the corresponding DOM node should be updated to reflect the change
  • Deletion: If an existing data item is removed, then the corresponding DOM node should also be removed
  • Creation: If a new data item is added, then a new DOM node should be created, appended to the correct place in the live DOM tree, and then linked as the corresponding DOM node for that data item

DOM reconciliation is a relatively simple process. We could easily create ShoppingListComponent ourselves with the ability to update/add/remove items, but it would be very highly coupled to the structure of the data and the DOM. The logic pertaining just to a singular update may involve, as we've seen, the specific mutation of a text node's content. If we want to change our DOM tree slightly or the structure of our data, then we have to significantly refactor our ShoppingListComponent.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.133.126.199