What is the DOM?
DOM stands for Document Object Model and is a programming interface for web documents. It defines the logical structure of documents and the way a document is accessed and manipulated. Elements of HTML become nodes in the DOM.
Example:
<table>
<tbody>
<tr>
<td>Shady Grove</td>
<td>Aeolian</td>
</tr>
<tr>
<td>Over the River, Charlie</td>
<td>Dorian</td>
</tr>
</tbody>
</table>
The DOM provides an interface (API) to traverse and modify the nodes. We can use different programming languages communicate with the method exposed by the DOM but web developers usually use JavaScript. Some example of methods are “getElementById” or “createElement”
const heading = document.createElement("h1");
const text = document.getElementById("content");
heading.appendChild(text);
Issues with the DOM
The HTML DOM is always tree-structured and this is great because we can traverse trees fairly easily. Unfortunately when the dom grows, modifying it becomes less and less efficient and slow.
With the arrival of new javascript frameworks and Single Page Applications, we need to modify the DOM tree incessantly and a lot.
React try to help in two ways: - Declarativeness: instead of traversing the DOM tree manually, you simple declare how a component should look like and React does the low-level job for you (the HTML DOM API methods are called under the hood) - Virtual DOM: is an abstraction of the HTML DOM. It is lightweight and detached from the browser-specific and helps to solve the performance issues.
What is Virtual DOM?
The Virtual DOM is a lightweight JavaScript representation of the DOM, you can think about it like a simplified copy of the HTML DOM.
It allows React (and other declarative frameworks) to do its computations within this abstract world and then synch with the “real” DOM. Updating the virtual DOM is infact faster than updating the actual DOM.
In summary, this is what happen when you update a component:
- The virtual DOM gets updated.
- The virtual DOM gets compared to a previous virtual DOM snapshot to figures out exactly which objects have changed (this process is called “diffing”).
- Only the changed objects get updated on the real DOM.
- Changes on the real DOM cause the screen to change.