ReactJS is a JavaScript library for building user interfaces. It is a component-based library that encapsulate your code in a component. Data can be passed into components, each component is specific and can manage it own state for storing data. The state is separated from the DOM. Components are rendered and its data is updated when the there is a change in the state.
Virtual DOM
Unlike other libraries, ReactJS builds a virtual representation of DOM element. This is a tree of JavaScript objects that represent the browser DOM.
ReactJS doesn't allow manipulation of the browser DOM, Instead you manipulate the virtual DOM which then result into the browser DOM.
Why Virtual DOM?
The reason for a virtual DOM is to enhance and optimize update to the actual virtual DOM.
In vanilla JavaScript, you manipulate the DOM using the typical DOM API selector, like document.getElementById
or document.querySelector
to select an HTML tag, and you can modify the tag using properties like .innerText
, innerHTML
, or .value
.
Although DOM manipulation is faster this way, it is still problematic because:
DOM changes causes the browser to reloaded. This is inefficient.
Recalculating and rendering layout after manipulation is slow
The virtual DOM is node tree of element and attributes just like the browser DOM. The node tree is created by React's render()
method from React components in response to change in React's data model.
When there is a change, the render()
method recreates the entire DOM, resulting to a new virtual representation of the DOM.
This involves a three-step process that optimizes the performance and makes the virtual DOM fast:
- It re-renders to new virtual DOM when there is trigger of change in the UI.
- The difference from the old virtual DOM and the new one will be recalculated to see what has changed.
- The browser is updated from the virtual DOM with what has changed.
Updating the actual DOM with new data from the virtual DOM is without reloading the browser is not only efficient but ideal. Although, it may seem like the virtual DOM would/should be slow because of the double render, and diffing of virtual DOM to see what has changed. The fact is that rendering the virtual DOM is more efficient than rendering UI in the actual browser DOM.
Virtual DOM Object
All elements in the virtual DOM are a function of ReactElement
.
ReactElement is a representation of DOM element in the virtual DOM. This is what is put in the "actual DOM" of the browser.
Conclusion
ReactJS among the three popular JavaScript libraries(React, Vue and Angular) has become de facto for front-end web development. Hence, it is vital to know how it works if you use it or plan to use it. There's more to know. If you want to know how React creates and builds the virtual nodes, you can find out more in the complete article here
Thank you for reading 🙏🏿
Top comments (0)