Dr. Greg Bernstein
Updated April 20th, 2021
const element = <h1>Hello, Web Development!</h1>;
ReactDOM.render(element, document.getElementById('root'));
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);
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)
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);
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…
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.”
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.
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.
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.
From Rendering Elements