Andrea Giammarchi shows us how to use his hyperHTML function as a fast and light virtual DOM alternative
Andrea Giammarchi walks you through his brilliant virtual DO M alternative
Before describing what’s new, incredibly simple and exciting on the horizon, let’s remember the main reason virtual DOM was created in the first place: Manual DOM manipulation is messy and keeping track of the previous DOM state is hard. A solution to this problem is to write your code as if you were recreating the entire DOM whenever state changes. Of course, if you actually recreated the entire DOM every time your application state changed, your app would be very slow and your input fields would lose focus. Taken directly from the original virtualdom libraries ( github.com/Matt-Esch/virtualdom#motivation), I believe we can all agree that manually targeting text nodes, attributes, inline styles or listeners isn’t exactly the coolest part of web development, is it? There are so many things that could go wrong and so much to take care of.
Some Historic Background First
Virtual DOM Basics
Since the DOM API is huge, and for many developers simply too complex, dealing with models, data or states, and being able to refresh automatically any view once updated, simply won the audience.
In short, you update your application state and the rest renders automatically, recycling behind the scenes everything that can be recycled on the DOM world. Developers don’t need to directly deal with the view anymore, they just define such a view once and deal with the data that generated it – nothing else. Most importantly, even if most Virtual DOM libraries advocate the glory of immutability, the DOM handled by these libraries is never regenerated or copied/duplicated from zero. The DOM handled by Virtual DOM libraries that advocate immutability is mutated every time it’s needed, because that’s the cheapest and fastest way.
Virtual DOM Logic
While the purpose is to focus on states and data from a developer point of view, the goal is to reflect these changes with the least amount of native DOM operations on the browser. This means that a list of users, shown inside a regular <li> element, shouldn’t be re-rendered if just one user on that list changes the address. ‘Diffing’ becomes the word that meaningfully describes what the Virtual DOM is about: tracking two different states and reflecting differences on the view.
In summary, Virtual DOM is, to simplify, an Array and Object traversing and comparing procedure, the aim of which is to find out which related node attribute, text content or subtree should be updated on the next render call.