Compare Reactjs’s VDOM with normal DOM

Lets create a simple example of ticking clock both in plain javascript code as well as react js code.

Here is the HTML which will have 2 divs to show clock time via normal JS code and reactjs code

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>React Demo</title>
<script src="https://unpkg.com/react@15/dist/react.js"></script> 

<script src="https://unpkg.com/react-dom@15/dist/react-dom.js"></script>
  </head>
  <body>
<div id="js"></div>
<div id="react"></div>
    <script src="script.js"></script>


  </body>
</html>

Now lets add the javascript code which will use plain JS code to update first div and react js code which will update second div every second

const jsContainer = document.getElementById("js");
const reactContainer = document.getElementById("react");
const render = () => {
  jsContainer.innerHTML = `
    <div class="demo">
      Hello JS
      <input />
      <p>${new Date()}</p>
    </div>
  `;
  ReactDOM.render(
    React.createElement(
      "div",
      { className: "demo" },
      "Hello React ",
      React.createElement("input"),
      React.createElement(
        "p",
        null,
        new Date().toString()
      )
    ),
    reactContainer
  );
}
setInterval(render, 1000);

One you run this code you will not be able to type anything in first textbox as whole div is getting re-rendered every second where you will be able to update second text box as in that case react is only updating the time stamp and not re-rendering other components within the div.

Here is own chrome’s console looks like. You can see in first case whole div is regenerating every second and in second case only timestamp component is getting re-rendered

Uday Ogra

Connect with me at http://facebook.com/tendulkarogra and lets have some healthy discussion :)

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *