JS: Create Your Own Virtual DOM #DIY
One fine day, when I was having a conversation with Sesh, he said, “We need to start writing Framework, instead of learning Framework”. This sentence gave me the enthusiasm for writing this post.
I have been working on React App Development for a year. If someone asks me to explain what a Virtual DOM is, I sure can whereas if I’m asked to create a Virtual DOM, I will say NO. But, now it got me thinking to write my own Virtual DOM.
P.S. This post doesn't give blah blah blah about React Virtual DOM. It is about my story of trying to implement a Minimal Virtual DOM using Plain JS.
Before that, here is a quick introduction. DOM is an object-oriented representation of the HTML, which can be modified with JS(DOM Manipulation). Sometimes, we may need to re-layout and re-paint the DOM tree, which is expensive and affects performance.
For that, Facebook uses Virtual DOM(a lightweight copy of the actual DOM) to React. Whenever the content gets changed, that changes will be made in Virtual DOM first. Then React will compare updated virtual DOM with current Virtual DOM and apply only patches into the actual DOM thus reducing the extra painting work.
To try out my Virtual DOM, I am going to create a Digital Clock with following requirements
- Time gets updated every second.
- Hour Minute separator & Minute Second separator color(props) get updated every second.
- A text will be displayed at the bottom whenever seconds value is divisible by 5
We will break down the task into simple tasks,
- Built a Virtual DOM Object and render it to the DOM.
- Update the Virtual DOM and compare it with current Virtual DOM and generate a patch list.
- Apply those patches to the DOM.
Note: I am using the Chrome Paint Flashing tool to track and verify repainting.
Task 1:
I had defined a structure for Virtual DOM and build a simple UI of Digital Clock.
Then wrote a function, which will convert the Virtual DOM JS Object into a DOM Object.
And render that converted DOM object.
Task 2:
Update data, properties, and layouts of the Virtual DOM as per the requirement. And write a function to compare it with the current Virtual DOM and generate the patches list.
Task 3:
Apply the patch changes to the Browser DOM as per the generated patch list. Ta-Daaaaaaaa
Check out the code here :
The written Virtual DOM is not a perfect one. But by writing, we have got an idea about how it works.
Some days you just have to create your own sunshine.
Thanks for reading! ❤️. Please let me know what you think about this.
Image Courtesy: Photo by Sergey Zhumaev from Pexels