Careeroza
Virtual DOM
What is the Virtual DOM?
The Virtual DOM is a lightweight JavaScript copy of the real DOM kept in memory. Changing the real DOM is slow; comparing two JavaScript objects is fast. So React updates the virtual copy first and then changes only the parts of the real page that are different.
User action (click / input)
↓
State changes
↓
New Virtual DOM is created
↓
Compared with the old Virtual DOM (diffing)
↓
Only the changed nodes are updated in the real DOM (reconciliation)
↓
UI updatedDiffing, Reconciliation and Fiber
- Diffing: the algorithm that compares the old and new virtual trees and finds the minimum changes.
- Reconciliation: applying those changes to the real DOM.
- Keys: help React match list items between renders (see Components → Lists).
- React Fiber: React's rendering engine (since React 16). It splits rendering work into small units so it can pause, prioritise urgent updates (typing) and resume later.
See It Work
Example
The clock re-renders every second, but only the text of the time changes in the real DOM. Type in the input: it keeps its value, because React does not recreate the whole page.
import { useState, useEffect } from 'react';
export default function App() {
const [time, setTime] = useState(new Date().toLocaleTimeString());
useEffect(() => {
const id = setInterval(() => setTime(new Date().toLocaleTimeString()), 1000);
return () => clearInterval(id);
}, []);
return (
<div>
<p>Time: <b>{time}</b></p>
<input placeholder="Type here while the clock ticks" />
</div>
);
}Result