Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does react update part of the DOM?

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,

like image 683
sir-haver Avatar asked Aug 30 '18 01:08

sir-haver


Video Answer


2 Answers

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.

like image 120
Robert Leonard Avatar answered Oct 10 '22 15:10

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.

like image 21
Hetal Rachh Avatar answered Oct 10 '22 14:10

Hetal Rachh