Create your own virtual DOM to understand it (Part 1)
Tags: hyperscript, javascript, virtualdom, react
Published: 2018-07-27 06:32:22

---
title: Create your own virtual DOM to understand it (Part 1)
published: true
tags: hyperscript,javascript,virtualdom,reactjs
canonical_url: https://aibolik.com/blog/create-your-own-virtual-dom-to-understand-it-part-1
---

In this article I want to recap my experience creating own “virtual DOM”. Sounds too ambitiously? Probably, but it is not that complicated as you might think. As the title states, it will make sense when you create your own, rather than reading thousands of articles about it.

_Originally, I was inspired by the talk of [Stefan Judis](https://medium.com/u/c3a0319fab53) at Web Rebels 2018, so feel free to take a look at it [_here_](https://youtu.be/kghSjWmNJyQ)._

This concept of **Virtual DOM** got popular back in 2013 when [React was released](https://reactjs.org/blog/2013/06/05/why-react.html). Because of this concept ReactJS is one of super fast libraries for building UI. I’ll try to explain it in few sentences, then we will get to writing own one.

> Virtual DOM is the representation of DOM as an object. When changes to state of application are made, new Virtual DOM is compared(applying [**diffing algorithms**](https://reactjs.org/docs/reconciliation.html)) with DOM and only changes are reflected, not causing full re-rendering of DOM.

Ok, here is a plan how we will create our virtual DOM.

1. Create _hyperscript_ function to render DOM — it is kinda [JSX](https://reactjs.org/docs/jsx-in-depth.html)
2. Create simple app with hyperscript
3. Make our App dynamic and learn to render virtual DOM
4. Implement diffing algorithm to see the power of virtual DOM

### HyperScript implementation

If you ever worked with ReactJS you probably know what is JSX. It can be another topic for discussion, but shortly it transforms “HTML-like” syntax into JavaScript function calls, in React it is transferred as React.createElement. So, in this step our aim is to _recreate_ this awesome function.

Generally, it is the building block that creates virtual DOM. However, in this step I want to emphasize how we can build simple DOM with it and in further steps we will develop it to make virtual DOM.

The inputs for this function are: _type of node, properties(a.k.a. attributes), children._ So here is a simple implementation of this function:

![](https://cdn-images-1.medium.com/max/1024/1*v7t7-08nG5TGJFSD0aaqVw.png)<figcaption>Implementation of <strong>hyperscript </strong>function, that constructs DOM given nodeName, attrs and children</figcaption>

Firstly, It simply creates DOM element with _nodeName._ Secondly, sets its attributes, and last step to append child nodes with the check for text nodes.

> **Note:** actually, we could go further and render children recursively, but I left this for later for simplicity reason.

Here is how it can be used(from now on we will use **_h_** instead of **_hyperscript_** ):

![](https://cdn-images-1.medium.com/max/500/1*dhtTJ-mXbjzWj6dsxvgfyQ.png)<figcaption>Simple function that renders h1 element</figcaption>

![](https://cdn-images-1.medium.com/max/544/1*yh4ESw-DoyojIG6KpY2BJw.png)<figcaption>Result of calling App() function</figcaption>

#### Creating application with Hyperscript

Okay, we now can create simple application with the help of Hyperscript. Let’s create a bit more complex application than it was in previous step. Here is our newer **_App_** function.

![](https://cdn-images-1.medium.com/max/984/1*Af-dWCO9YL2_2I37m-AEgA.png)<figcaption>“Complex Application” with hyperscript</figcaption>

When the **App** is executed it creates a _div,_ with two children: one rendering H1 heading, and the second one unordered list. Note that we pass **_props_** to our function and render **props.list** into unordered list. Let’s add some more rendering magic:

![](https://cdn-images-1.medium.com/max/1024/1*oarZn_WhFoBFQh1LghDUcA.png)<figcaption>Render the app with the state</figcaption>

Generally, we just want to render the output of **App** function(that is valid DOM) into the body of document giving the state that contains emojis list.

![](https://cdn-images-1.medium.com/max/577/1*g0mDXTJMoiVsJ4dPtjXK0A.png)<figcaption>Result of our work</figcaption>

_It wasn’t that hard. Is it?_ Let’s add some dynamic content, and add random emoji every 1 second this way we can see how our app renders.

![](https://cdn-images-1.medium.com/max/856/1*gpnljAXNujX8Lkl1JRTEUw.png)

![](https://cdn-images-1.medium.com/max/680/1*ltA2Y6YhMq8y2s5Kz39C0g.gif)<figcaption>DOM is fully re-rendering every 1 second</figcaption>

#### Implement vDOM rendering

Okay, now we have dynamic app done with _hyperscript_ let’s move on to actual virtual DOM and its implementation. First of all we need to change our _hyperscript_ function. Now it should not create real DOM, but instead it rather should create virtual DOM. So, given _nodeName,_ _attributes_ and _children_ we just a create an object with corresponding keys. Thanks to ES6 we can do this in one line:

![](https://cdn-images-1.medium.com/max/1024/1*kZpNI6nl6KVQjfFj2ewY6Q.png)<figcaption>hyperscript<em> function that returns virtual DOM</em></figcaption>

We have a virtual DOM and if we execute the **App** function with same emojis list we get something like this(logged in console):

![](https://cdn-images-1.medium.com/max/663/1*HYsUARTHUNuhAe5uvPeEig.png)<figcaption>Virtual DOM of our application</figcaption>

Pretty similar to DOM. Now let’s create a function that renders virtual DOM into real DOM. As you might have guessed it should take _virtual Node_ as a parameter. Here it is:

![](https://cdn-images-1.medium.com/max/1024/1*QkHR2QSgoAvuwkv406bf3Q.png)<figcaption>This function renders real DOM(DOM Node) given virtual DOM(Node)</figcaption>

Let me explain what it does step by step:

1. Using destructuring we retrieve nodeName, attributes and children of virtual Node
2. If vnode is text(we can check it by _vnode.split_) then we return text Node
3. Otherwise we create an element with nodeName and set its attributes from _attributes_ object
4. Do the same thing for children if any

Now, remember our _render_ function that rendered our **App**? We just need to change a little bit to make it work:

![](https://cdn-images-1.medium.com/max/812/1*PlV4Puh-8DuuL5ZI1lD6hg.png)

> This article became a bit longer than I thought, so I decided to break into two parts.

So, let’s recap this. We created a **hyperscript — ** _virtual DOM factory_ **, renderNode — ** _that turns virtual DOM into DOM element_ and a _function component_ **_App_** that creates whole page. The result is now the same as we did it before without virtual DOM, but now we have more control. In the next article we will explore what makes React(and virtual DOM) so fast.

_You can look up all steps in my_ [_GitHub repository_](http://bit.ly/2NKXH0V)_. You can find these steps in branches._

In the next article we will implement simple **diffing algorithm** , that will make our app faster and you’ll be able to see it action.

_UPDATE: Hey there, if you liked it go and take a look at the [2nd part of this article](https://dev.to/aibolik/create-your-own-virtual-dom-to-understand-it-part-2-nlc)!_

_UPDATE 24.11.2019: If you want to learn React by doing many exercises, feel free to sign up to my upcoming course [30-day-react](https://aibolik.github.io/30-day-react/)._