top of page
Logo der Online Agentur mdwp

Virtual DOM

React Js term "Virtual DOM" (VDOM) is a programming concept where an ideal or "virtual" representation of a UI is kept in memory and synced with the real DOM (Document Object Model) by a library such as React DOM.

The process involves the following steps:

1. Whenever any underlying data changes, the entire UI is re-rendered in the Virtual DOM representation.
2. Then, the difference between the previous or old Virtual DOM representation and the new one is calculated.
3. Once the calculations are done, the real DOM will be updated to reflect only those changes.

The ability to track and limit the changes made in the real DOM is at the heart of the higher performance React provides. This process is often referred to as "diffing" and "reconciliation".

Here's a quick example:

Suppose you have a list that needs to be modified based on user input. Instead of re-rendering the entire list in the DOM each time, React will build a new virtual representation of that list. Through diffing, React can identify which items in the list changed. And with reconciliation, React will only update those changed items in the real DOM, rather than re-rendering the entire list.

This is an oversimplification, but it demonstrates the basic principle of how React's Virtual DOM works to improve efficiency and speed.

An example of code reacting to state changes using virtual DOM is:

class App extends React.Component {
constructor(props) {
this.state = {
name: 'John Doe'

render() {
return (
<h1>Hello, {}</h1>
<button onClick={ () => { this.setState({ name: 'Jane Doe' }) } }>
Change Name

In this example, when the button is clicked, the `name` state changes. This change triggers a re-render. However, instead of re-rendering the whole components, React uses the Virtual DOM to only update the `<h1>` tag with the new name.

bottom of page