Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript React Basics (retired) First Steps in React State and the Virtual DOM

Michael Kalmykov
Michael Kalmykov
8,919 Points

How is react more preformant? it sounds like it's building two doms.

it seems like it'd take the time to build the virtual dom, and then take the time to build the real dom

2 Answers

Michael Liendo
Michael Liendo
15,326 Points

React first builds its virtual DOM then determines, based on changes that occur in the application, how the DOM should be rendered. So imagine you have a list of 100 items. Each item is an object. On a real DOM, if a change was made (say you updated one of the objects) then the entire DOM would be re-rendered ie) all 100 objects.

In React, because all of the changes are made on the virtual DOM, React says, "Ok, we see that you only made a change to 1 object, so instead of re-rendering the entire DOM all over again, I'm just going to re-render this one object."

Also, (a lesser know fact) is that React takes all user input and converts it to a String. Might not seem like a big deal at first glance, but what that means is that malicious injections (someone typing in code to try and access your code) are prevented. Another advantage of working with a virtual DOM.

Thanks for the great information. Would you mind elaborating on how converting to a string (I'm assuming it uses stringify?) can prevent malicious injection? Does it have something to do with the fact that a user can't simply inspect elements and view everything since a portion of the DOM is virtual?

Sachin P
Sachin P
79 Points

Why isn't the DOM not already doing this? If DOM could perform the comparison then the virtual DOM can be eliminated right?

Please elaborate on how malicious injections are prevented by react converting input to string

Keith Dowd
Keith Dowd
4,404 Points

@eikaodell My understanding is that converting all user input to a string makes it so that code injected into user input components (e.g., input fields, text areas, etc.) will not and cannot be executed by the JavaScript engine. For example, it prevents the use of eval() statements to execute malicious code.

@Sachin P This is a good question. I think it's just the reality that browsers cannot keep pace with innovation.

How can eval execute malicious code?