Rendering Elements
# 02. Rendering Elements
Elements are the smallest building blocks of React apps. They describe what you want to see on the screen.
const element = <h1>Hello, world</h1>;
Unlike browser DOM elements, React elements are plain objects that are cheap to create. React DOM takes care of updating the DOM to match the React elements.
# Rendering an Element into the DOM
Assume there is a <div> somewhere in your HTML file:
<div id="root"></div>
This is the root node. A React application has only a single root DOM node.
However, an HTML page can have multiple React applications, each corresponding to an independent root node.
const el = <h1>Hello</h1>
ReactDOM.render(el, document.getElementById('root'))
2
# Updating the Rendered Element
React elements are immutable (opens new window). Once created, you cannot change its children or attributes. An element is like a single frame in a movie: it represents the UI at a certain point in time.
With our knowledge so far, the only way to update the UI is to create a new element and pass it to ReactDOM.render() (opens new window).
Consider a ticking clock example:
function tick() {
// element is a React element
const element = (
<div>
<h1>Hello, world!</h1>
<h2>It is {new Date().toLocaleTimeString()}.</h2>
</div>
);
ReactDOM.render(element, document.getElementById('root'));}
setInterval(tick, 1000);
2
3
4
5
6
7
8
9
10
11
Note: In practice, most React apps only call ReactDOM.render() (opens new window) once. In the next section, we will learn how to encapsulate such code into stateful components (opens new window).
# React Only Updates What's Necessary
In the previous example, even though we create a new element describing the entire UI tree on every tick, React DOM only updates the content that has actually changed.