Source:  Twitter logo

I know that this subject has been discussed a lot obviously, but I'm not sure how to research my question that is rather specific and I hope it follows the rules here.

I know that to decide whether to update the DOM or not, react compares the virtual DOM with the re-rendered one. But I just didn't understand if in case it does decide to update it - does it update all the elements of the specific re-rendered component, or does it know to update only the changed elements of the componenet?

Thanks in advance,

A good place to get a better understanding of how react decides to re-render elements is the reconciliation documentation but I can summarize:

Every time render() is called react will create a new virtual DOM where the root node is the component whose render function is called. The render() function is called when either the state or the props of a component or any of its children change. The render() function destroys all of the old virtual DOM nodes starting from the root and creates a brand new virtual DOM.

In order to make sure the re-rendering of components is smooth and efficient React uses the Diffing Algorithm to reduce the time it takes to create a new tree to a time complexity of O(n), usually time complexity for copying trees is > O(n^2). The way it accomplishes this is by using the "key" attribute on each of the elements in the DOM. React knows that instead of creating each element from scratch it can check the "key" attribute on each node in the DOM. This is why you get a warning if you don't set the "key" attribute of each element, React uses the keys to vastly increase its rendering speed.

13 users liked answer #0dislike answer #013
Robert Leonard profile pic
Robert Leonard

Execution of the render() method does not mean that react also renders the actual DOM. React keeps two copies of the virtual DOM i.e. the old virtual DOM and the re-rendered virtual DOM which gets created when the render() method is called.

The output of the render() method is a javascript object which is mapped to a DOM element. When a component is changed, we get a new react element. It then compares the new react element and its children in the re-rendered virtual DOM with the element and its children in the old virtual DOM. If any differences found, it then updates the real DOM only at the places where something has changed (e.g Text of the button has changed) and not update the entire real DOM. If no differences found, the real DOM is not touched.

8 users liked answer #1dislike answer #18
Hetal Rachh profile pic
Hetal Rachh

Copyright © 2022 QueryThreads

All content on Query Threads is licensed under the Creative Commons Attribution-ShareAlike 3.0 license (CC BY-SA 3.0).