React Elements

Daneesha Bartholomeusz
2 min readSep 15, 2021

--

React elements are the smallest building blocks of a React application. They’re objects (DOM elements are not). Therefore they’re not expensive to create. The React DOM updates the DOM to match React elements.

Elements are used to control the UI flow. They describe what has to be shown on the screen. (They represent the interface).

An example for an element;

const element = <h1>Hello World!</h1>;

Elements vs Components

Elements are what components are made of.

Rendering Elements

<div id=“root”></div>

An HTML file can contain the above code. (A root DOM element)

const element = <h1>Hello World!</h1>;ReactDOM.render(element, document.getElementById(‘root’));

You can render and element as above.

Updating Rendered Elements

Elements are immutable. So to update one you have to create a new element and pass it to the render method.

Here’s an example taken from React Docs.

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);

React DOM compares each element on the tree to its previous version and only updates if necessary. This is the secret of React’s fastness.

Traditional UI Model

In the traditional UI model each component keeps a references to its DOM node and its children. And have to create, update, destroy them. It becomes hard to decouple things because each parent has a reference to its children.

React Model

An element is an object. It describes a component instance or a DOM node. You can’t call methods on it. You can say that it’s an immutable description object. It has two fields, type and props.

If the type is a string the element represents a DOM node, and if the type is a function the element is a component.

Elements can be nested and be created into a tree structure. In this tree Both parent and children are objects. It’s easy to traverse this tree. No parsing is required. And the tree parts are lighter than DOM elements.

Component Elements

  1. An element can describe a DOM node
  2. An element can also describe a component

It is possible to have DOM elements and component elements in the same tree. Each part of this tree expresses relationships through composition. Therefore the parts are decoupled. Because different types are part of the same tree you can construct parts of UI independently. This is why React is said to be fast.

Reconciliation

The way React composes the component tree is called reconciliation. It’s a top down process where React asks each item what its children are. This helps to update parts of the application only, the necessary parts. This helps React work very fast.

--

--

No responses yet