[React MAIN CONCEPTS] 3. Rendering Elements

Rendering Elements

Elements are the smallest building blocks of React apps.

An element describes what you want to see on the screen:

1
const element = <h1>Hello, world</h1>;

Unlike browser DOM elements, React elements are plain objects, and are cheap to create. React DOM takes care of updating the DOM to match the React elements.

Rendering an Element into the DOM

Let’s say there is a <div> somewhere in your HTML file:

1
<div id="root"></div>

We call this a “root” DOM node because everything inside it will be managed by React DOM.

Applications built with just React usually have a single root DOM node. If you are integrating React into an existing app, you may have as many isolated root DOM nodes as you like.

To render a React element into a root DOM node, pass both to ReactDOM.render():

1
2
const element = <h1>Hello, world</h1>;
ReactDOM.render(element, document.getElementById('root'));

Try it on CodePen - https://reactjs.org/redirect-to-codepen/rendering-elements/update-rendered-element

It displays “Hello, world” on the page.

Updating the Rendered Element

React elements are immutable. Once you create an element, you can’t 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().

Consider this ticking clock example:

1
2
3
4
5
6
7
8
9
10
11
function tick() {
const element = (
<div>
<h1>Hello, world!</h1>
<h2>It is {new Date().toLocaleTimeString()}.</h2>
</div>
);
ReactDOM.render(element, document.getElementById('root'));
}

setInterval(tick, 1000);

Try it on CodePen - https://reactjs.org/redirect-to-codepen/rendering-elements/update-rendered-element

It calls ReactDOM.render() every second from a setInterval() callback.


Note:

In practice, most React apps only call ReactDOM.render() - https://reactjs.org/docs/react-dom.html#render once. In the next sections we will learn how such code gets encapsulated into stateful components - https://reactjs.org/docs/state-and-lifecycle.html.


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.

You can verify by inspecting the last example with the browser tools:

DOM inspector showing granular updates

Even though we create an element describing the whole UI tree on every tick, only the text node whose contents have changed gets updated by React DOM.

References

[1] Rendering Elements – React - https://reactjs.org/docs/rendering-elements.html

[2] React – A JavaScript library for building user interfaces - https://reactjs.org/