-
Notifications
You must be signed in to change notification settings - Fork 25
Virtual Dom benefits
A virtual DOM gives 3 main benefits over traditional DOM manipulation:
- Declarative UI
- Guaranteed only one page reflow per render for nearly everything
- Easy event handling
One of the hardest things about some UIs is transitioning between app states. If you're manipulating the DOM on your own, you have to write your own code for that transition. If you can transition from both state A and B to state C (for example, if you can checkout from both a cart and from a buy-now button in an ecommerce app), you have to write code to handle both transitions — taking away existing DOM nodes and adding others is probably a different process depending on whether you're coming from A or B.
In all cases, though, a virtual DOM is declarative. You only need to specify what it needs to look like. You can go from any state to any state in a single line of code (in the case of a Clearwater app: app.render). This is extremely helpful if your app updates in real time over a websocket and multiple updates come in between renders. One render pass and it's up to date.
Page reflows are necessary for rendering. If they never happen, your UI will never update. However, they're slow, so the optimal number of reflows per render is 1.
Rendering via DOM manipulation in something like Backbone usually triggers page a reflow for each view. Each view has to find its container in the DOM and render its template into it. That's a read/write for every single view throughout your entire rendering process. If you're only updating a single view that has no child views, that's not such a big deal, but if you're updating a large container view with a wide or deep tree of descendants, you can easily trigger 100 reflows in a single render.
A virtual DOM guarantees a single reflow per render, no matter how complex your UI is. These generally happen in 50-100ms even on slow devices for apps whose UIs aren't overly complicated, so if your UI updates primarily through a user clicking through the app, you can probably get away with the performance of interleaved reads/writes.
If you assign event handlers during render with things like onclick, for example, you can use the component as the context for the handler and all event handlers for that particular DOM node are right there for you to see. You don't have to go searching through a separate piece of code to see where all the handlers are.
This is a tradeoff, though, because sometimes it's also nice to see all your event handlers in one place. I've never missed that, to be honest, but it was a nice perk sometimes. I actually prefer the onclick way after using it for a while.