React Rendering

Dr. Greg Bernstein

September 17th, 2019

React Rendering

Readings

Rendering an Element


const element = <h1>Hello, Web Development!</h1>;
ReactDOM.render(element, document.getElementById('root'));

Digression: Repeating over time

From MDN setInterval:

  • The setInterval() method repeatedly calls a function or executes a code snippet, with a fixed time delay between each call. Returns an intervalID.

  • Example: var intervalID = window.setInterval(func, delay);

Digression: Turning it off

From MDN clearInterval

  • The clearInterval() method cancels a timed, repeating action which was previously established by a call to setInterval().

  • E.g.: window.clearInterval(intervalID)

Updating a React Element

From examples branch rendering

function windSpeed() {
  return 25 * Math.random();
}

function tick() {
  const element = (
    <div>
      <h1>Hello, world!</h1>
      <h2>It is {new Date().toLocaleTimeString()}.</h2>
      <p>The windspeed is {windSpeed().toFixed(1)}.</p>
    </div>
  );
  ReactDOM.render(element, document.getElementById("root"));
}
setInterval(tick, 1000);

This seems inefficient

  • We are telling React to re-render the entire element, a <div> containing <h1> and <h2> elements just because a time and wind string changes.

  • Let’s run this and see how bad things are…

What’s Going On Here?

From Rendering Elements

  • “React Only Updates What’s Necessary”

  • “React DOM compares the element and its children to the previous one, and only applies the DOM updates necessary to bring the DOM to the desired state.”

The “Virtual DOM”

From React: The Virtual DOM

  • In React, for every DOM object, there is a corresponding “virtual DOM object.” A virtual DOM object is a representation of a DOM object, like a lightweight copy.

  • A virtual DOM object has the same properties as a real DOM object, but it lacks the real thing’s power to directly change what’s on the screen.

The “Virtual DOM”

From React: The Virtual DOM

  • Manipulating the DOM is slow. Manipulating the virtual DOM is much faster, because nothing gets drawn onscreen.

  • When you render a JSX element, every single virtual DOM object gets updated.

The “Virtual DOM”

From React: The Virtual DOM

  • Once the virtual DOM has updated, then React compares the virtual DOM with a virtual DOM snapshot that was taken right before the update.

  • Once React knows which virtual DOM objects have changed, then React updates those objects, and only those objects, on the real DOM.

Big “take away”

From Rendering Elements

  • “In our experience, thinking about how the UI should look at any given moment rather than how to change it over time eliminates a whole class of bugs.”