Table of contents
How does react know what needs to be changed or updated in the current UI?
What is a DOM?
DOM (Document Object Model) is a representation of aπtree like structure that contains nodes. The DOM can be manipulated by the programmers π΄π»as required. The DOM is created by the browser π itself. Every time there is a change in UI, the DOM representation changes.
render()
The render function renders a tree of react elements, when the props or state changes, the render()
function will render a new tree of react elements.
Virtual DOM (VDOM)
As the name suggests a DOM which is virtual is called Virtual DOM, Umm, sounds abysmal & horrendous to me! isn't it? Let's see, further ahead!
ποΈπποΈ
The Virtual DOM is a virtual representation of the DOM which is kept in memory and it depicts the current representation of the UI. It is also used for comparison with the newly created DOM after any update in the UI, so that React can come to know what changes have been made after any update.
Reconciliation
The whole process π of comparison of π Virtual DOM with the newly created DOM and finding out, what changes need to be made while updating the UI is called reconciliation. πΆβ’οΈ
Diffing Algorithm
The algorithm which is used to compare the differences between the Virtual DOM and the newly created DOM is called Diffing Algorithm
. Using this we can also find out what needs to be changed in the DOM & UI.
1. Whenever the root nodes of the VDOM & DOM are different, React will destroy/tear down the whole tree and create a new tree from scratch using which, the UI will be updated.
2. Whenever the root nodes are identical, React will keep the similar nodes in the tree and update only those nodes, which are different, using which the UI will be updated.
Key
React supports the key attributes for the children elements using which all the children nodes can be identified uniquely, and in case of any addition or deletion of these children nodes, react will exactly come to know what changes need to be performed in various nodes. And these changes will be reflected in the tree and the UI will update eventually.
Note - In general, the index value is not recommended to use as a key attribute. The key attribute for every children node should be unique and the index should be used as a last resort in case of the absence of any unique element.
Unique key attribute (not index) >>> Unique index attribute >>>>>> No key.
Hope you liked it, Thanks for being here, all the best!