Search code examples
reactjsvirtual-dom

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,


Solution

  • 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.