What is the DOM and Virtual DOM?
When a web page is loaded the browser creates what is known as a Document Object Model or DOM. The DOM consists of a tree of objects containing elements (e.g html → body → h1), once created we can then interact with these HTML elements and execute Javascript.
For example we could select an element using ‘document.getElementbyId()’ and then use Javascript to change the background colour.
The virtual DOM on the other hand is something that is used by React to help determine what has changed in your app and make updates accordingly. The Virtual DOM is almost identical to the real DOM and is used by React to identify what has changed and what has kept the same so it knows what needs to be re-rendered.
Below is an example of the general steps React will take when updating a component.
- When a change occurs a Virtual DOM is created containing all the elements in your app.
- React will compare the Virtual DOM with the real DOM to see what has changed (uses a differing algorithm to do this).
- Once changed components have been identified React will then only update these components in the real DOM, this is very effective as React is not having to update/re-render every element.
- After the DOM has been updated the screen and UI will also get updated and changes will be visible to the user.
The DOM and Virtual DOM are key to how React works and is a very efficient way to create and update your application.