Search code examples
javascripthtmlreactjsdomvirtual-dom

How is React able to only update single part of the real DOM tree?


How is React's Virtual DOM able to only render a certain part of the DOM & keep the rest of the tree?

Not sure if I'm correct, but if I change content of a Div in a normal HTML file, I would have to refresh the page to see the changes, right? Meaning I would have to repaint the whole thing, recreate the whole DOM tree again. I can't just directly update "only" the Div element myself. I will need to refresh the page & recreate the whole tree.

I know what Virtual DOM is, how it compares new version to it's old, diffing & stuff like that. I also read the reconciliation document, but that didn't answer my question as well. What happens after React has the new Virtual DOM it needs to convert into the Real DOM?

What I'm trying to ask is: Essentially, React is just plain HTML & JS, having to end up as the real DOM. So how do they only update a Single Div element in the DOM instead of needing to reload the whole page? Because if we did that manually in HTML, the whole page would need to be refreshed to see changes & as far as I know, we can't just update one part of it ourselves like React does.


Solution

  • The short answer is that you don't have to reload the page to update the DOM tree. You can try this yourself by inspecting any element and edit its contents. React can also update the DOM in a similar way. It's instant as the contents are in memory and not saved on a file (which would need to be reloaded).

    Example of a DOM update :)

    enter image description here