DOM stands for Document Object Model. It is the hierarchical representation of the web page(UI). Virtual DOM is just a copy of the original DOM kept in the memory and synced with the real DOM by libraries such as ReactDOM. Because DOM manipulation is very slower and expensive in terms of time complexity.
When there is a update in the virtual DOM, react compares the virtual DOM with a snapshot of the virtual DOM taken right before the update of the virtual DOM.
With the help of this comparison React figures out which components in the UI needs to be updated. This process is called diffing. The algorithm that is used for the diffing process is called as the diffing algorithm.
<div> <divclass="diff"> <h2>hello</h2><inputtype="text"><span>now:21:58:08 GMT+0800 (China Standard Time)<inputtype="text"></span> </div> <divclass="key"> <h2>Person Information List</h2><button>Add one people</button> <h3>using index as key</h3> <ul> <li>Alex---18<inputtype="text"></li> <li>Allen---19<inputtype="text"></li> </ul> <hr> <hr> <h3>using id as key</h3> <ul> <li>Alex---18<inputtype="text"></li> <li>Allen---19<inputtype="text"></li> </ul> </div> </div>
The span in diff class will change every 1 second, but another html element won’t change in this class section, that is the help from diffing algorithm.
The key section, if use index as key, it can’t get benifit from diffing because the index was changed and will force evey li to render it again and again. If use the id as key, the performace will revert, because the id is unique and stable for every li.
Frequent DOM manipulations are expensive.
Virtual DOM is a virtual representation of DOM in memory.
Virtual DOM is synced with real DOM with ReactDOM library. This process is called Reconciliation.
React compares the Virtual DOM and pre-updated Virtual DOM and only marks the sub-tree of components that are updated. This process is called diffing.
The algorithm behind diffing is called Diffing algorithm.React uses keys to avoid unnecessary re-renders.
const handleClick = (e: any) => { console.log(`this is passed any parameter:${e}`); console.log(`this is from e.id:${e.target.id}`); console.log(`this is e.data:${e.currentTarget.getAttribute('data-xxx')}`); }