Virtual DOM is a lightweight JavaScript object, which is an in-memory representation of a real DOM. It is an intermediary step between the render function being called and the displaying of elements on the screen. It is similar to a node tree, which lists the elements, their attributes, and content as objects and their properties. The render function creates a node tree of the React components and then updates this node tree in response to the mutations in the data model caused by various actions done by the user or by the system.
Virtual DOM works in three steps:
- Whenever any data changes in the React App, the entire UI is re-rendered in Virtual DOM representation.
- Now, the difference between the previous DOM representation and the new DOM is calculated.
- Once the calculations are completed, the real DOM updated with only those things which are changed.
In React Native, the concept of Virtual DOM is similar to that in React for the web. However, there are some nuances due to the differences in the underlying architecture between React for the web and React Native.
Here’s how the Virtual DOM works in React Native:
- Component Tree Representation:
- Just like in React for the web, React Native maintains a virtual representation of the UI components, known as the Virtual DOM. This is essentially a lightweight copy of the actual UI components.
- Rendering Process:
- When there is a state or props change in a React Native component, a new virtual representation of the UI is created.
- Differential Reconciliation:
- React Native uses a process called “differential reconciliation” to efficiently update the actual UI. Instead of updating the entire UI, it calculates the minimal number of changes needed and applies those changes to the native components.
- Bridge Communication:
- React Native operates in a bridge-based architecture, where JavaScript code runs in a separate thread from the native UI thread. When changes are calculated in the Virtual DOM, they are communicated to the native side through the bridge, and the native components are updated accordingly.
- Asynchronous Updates:
- React Native batches UI updates and sends them to the native side asynchronously. This helps in optimizing performance by reducing the number of times the bridge is crossed.
- UI Thread Interaction:
- The actual rendering of native components takes place on the UI thread of the device. The Virtual DOM helps in minimizing the work done on this thread by calculating the most efficient updates.
It’s important to note that React Native’s implementation of the Virtual DOM is tailored to work with native components and the specific challenges posed by mobile platforms. While the core principles are similar to React for the web, the details of how updates are processed and communicated to the native side differ to accommodate the unique aspects of mobile development.