DOM Traversal in React

Before React came along, manipulating what we see in the webpage was done by Javascript or Jquery, a library for Javascript. Both Javascript and Jquery manipulated webpage by going into the DOM tree, picking out the elements that were selected to be changed, and then applying the changes by re-rendering the DOM tree with newly changed elements.

Jquery, in particular, was and still is, a popular choice for DOM traversal & manipulation because it makes the process easy and intuitive with commands such as .click() and .toggleClass(), as opposed to Javascript’s .addEventListener(‘click’) and getting class by name and changing class. In addition, Jquery provides ease of transferring data between client and server. Just compare the code required for Javascript’s XMLHttpRequest versus Jquery’s $.get() or $.post().

In 2013, Facebook created and introduced React, also a Javascript library. Its selling point was that it was simple, scalable, and fast. In today’s topic, I will be covering why React is fast, in relation to DOM traversal & manipulation.

The biggest reason why React is fast at DOM traversal & manipulation is that it minimizes DOM traversal & manipulation. This sounds odd at first… one would think that if number of manipulations keep accumulating and happen all at once, it would slow down the application. However, React is different from Javascript and Jquery in that React implements Virtual DOM.

Virtual DOM is just a copy of DOM tree itself, and React does traversal & manipulation only on the virtual DOM. React only manipulates the actual DOM after applying the changes in the Virtual DOM and copying that into actual DOM. It is important to note that only the elements that was changed gets re-rendered, so the elements that was not changed does not get updated again, in contrast to Jquery and Javascript. Most importantly, note that because React is a Javascript library, one can write DOM manipulation code such as document.getElementById(), and it would work in React applications. However, because such commands actually manipulate DOM itself, you are not leveraging React’s strength, which defeats the purpose of React. Therefore, one should never use Javascript/Jquery DOM manipulation codes in React, and instead, should use state to paint a picture of what the result of change is going to be.

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.