From JSX to the DOM

React provides a seamless way to transform JSX elements into actual DOM elements within your HTML document. Understanding this process removes any mystery about how JSX interacts with the browser.

Think of React as a translator: it takes JSX code, builds a virtual representation of the UI (the Virtual DOM), and then efficiently updates the real DOM based on changes. This approach enhances performance by minimizing unnecessary updates.

Creating Elements with JSX

JSX allows developers to create virtual DOM elements using an HTML-like syntax.

Example

const ExampleComponent = props => (
  <>
    <h1>Hello!</h1>
    <img src="https://via.placeholder.com/150" />
    <a href={props.searchUrl}>{props.searchText}</a>
  </>
);
    

This function returns a JSX fragment containing three elements:

These elements exist in the Virtual DOM until React converts them into real DOM elements.

Rendering JSX to the DOM

React takes JSX elements and renders them into the real DOM using ReactDOM.createRoot().render(). The render method inserts the transformed JSX content into a specified root DOM node.

Example

// Get a real DOM node for React to render into
const mainElement = document.querySelector('main');

// Render JSX into the main element
ReactDOM.createRoot(mainElement).render(
  <ul>
    <li className="selected">
      <a href="/pets">Pets</a>
    </li>
    <li>
      <a href="/owners">Owners</a>
    </li>
  </ul>
);
    

In this example:

From Virtual DOM to Real DOM

When React processes a JSX element tree, it performs the following steps:

  1. Converts JSX elements into a Virtual DOM structure.
  2. Compares the new Virtual DOM with the previous Virtual DOM.
  3. Identifies the minimal number of changes needed.
  4. Efficiently updates only the necessary elements in the real DOM.

For example, if you remove the className="selected" from the first <li> and call render again, React will detect this change and only remove that class from the real DOM, rather than rebuilding the entire list.

Virtual DOM Diffing

React uses a process called "reconciliation" to compare the old and new Virtual DOM trees, ensuring that only the necessary changes are applied.

Before Update

<ul>
  <li class="selected"><a href="/pets">Pets</a></li>
  <li><a href="/owners">Owners</a></li>
</ul>
    

After Update (Removing selected Class)

<ul>
  <li><a href="/pets">Pets</a></li>
  <li><a href="/owners">Owners</a></li>
</ul>
    

Instead of reloading the entire <ul>, React only modifies the necessary <li> element.

Understanding React’s Efficiency

React optimizes performance by:

This is why React applications feel fast and responsive even as they grow in complexity.

Wrapping Up

In this tutorial, you learned:

By understanding how React transforms JSX into actual DOM elements, you can build fast, interactive, and efficient web applications with confidence.