React Behind the Scenes: How It Works

Vedesh K V S - Oct 9 - - Dev Community

React is undoubtedly the most popular JavaScript library for building large-scale web applications, and understanding how it works behind the scenes can give you a deeper insight into its power and simplicity. Let's dive into the mechanics of React, starting with how JavaScript can manipulate HTML, and how React improves this process.

Building HTML with JavaScript: The Traditional Way

Typically, we can modify the DOM (Document Object Model) using JavaScript by interacting with HTML elements. For example:

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

<script>
const heading = document.createElement("h1");
heading.innerHTML = "Hello World from JS";
const root = document.getElementById("root");
root.appendChild(heading);
</script>
Enter fullscreen mode Exit fullscreen mode

In the example above:

  • We create a new <h1> element.
  • We add content ("Hello World from JS") to it.
  • Finally, we append the new element to the DOM.

This works, but it can get cumbersome as the project grows. This is where React simplifies things.

Enter React: Bringing Structure to the Chaos

React is a JavaScript library that allows developers to efficiently manage the UI. Since browsers don't understand React by default, we need to load React into our project. One easy way is to use CDN (Content Delivery Network) links:

  1. React CDN: Core React library.
  2. React DOM CDN: Handles updating the DOM, which is crucial for web applications.

These CDNs bring React’s superpowers into our project, allowing us to create and manage DOM elements programmatically.

Creating HTML Elements with React

Just like we can create HTML elements using JavaScript's document.createElement, React offers its own method to create elements:

const heading = React.createElement("h1", {}, "Hello World From React!");
Enter fullscreen mode Exit fullscreen mode

React.createElement takes three arguments:

  1. Tag: The HTML element you want to create (e.g., "h1").
  2. Attributes: An object that specifies attributes like id, class, etc.
  3. Children: The content inside the element.

Rendering the Element in the DOM

After creating an element, React still needs a place to render it, and that’s the job of ReactDOM:

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(heading);
Enter fullscreen mode Exit fullscreen mode

Here, ReactDOM.createRoot creates a virtual root for React to manage the DOM modifications, and root.render() renders the React element into the DOM.

Why React?

The philosophy behind React is to manipulate the DOM efficiently using JavaScript. Manipulating the DOM is one of the most expensive operations in terms of performance on a webpage. React minimizes the number of direct DOM manipulations, using a virtual representation of the DOM (called the virtual DOM) to batch changes and make updates more efficient.

Adding Styles with CSS

Now that we have the power of React, we can style our elements using regular CSS. For example:

#heading {
    color: red;
}
Enter fullscreen mode Exit fullscreen mode

This will change the color of the heading created by React, just like traditional HTML and CSS. The key difference is that React handles the element creation in a structured, maintainable way.

Creating Nested and Sibling Elements

React allows us to easily create nested elements or even sibling elements. For example, to create nested elements:

const parent = React.createElement("div", {id: "parent"}, 
    React.createElement("div", {id: "child"}, 
    React.createElement("h1", {}, "I am an H1 Tag")));
Enter fullscreen mode Exit fullscreen mode

This creates a nested structure, but React can also handle siblings by passing them as an array:

const parent = React.createElement("div", {id: "parent"}, 
    React.createElement("div", {id: "child"}, 
    [heading, React.createElement("h1", {}, "I am an H1 Tag")]));
Enter fullscreen mode Exit fullscreen mode

However, when rendering lists of sibling elements, React warns you if they don’t have a unique key prop. This key helps React optimize its rendering process:

Warning: Each child in a list should have a unique "key" prop.
Enter fullscreen mode Exit fullscreen mode

Nesting and Sibling Elements: The Ugly Way

It’s possible to nest multiple elements using React.createElement, but it quickly gets messy:

const parent = React.createElement("div", {id: "parent"}, 
    [React.createElement("div", {id: "child"}, 
    React.createElement("h1", {}, "I am an H1 Tag"),
    React.createElement("div", {id: "child2"}, 
    React.createElement("h2", {}, "I am an H2 Tag")))]); 
Enter fullscreen mode Exit fullscreen mode

While this works, it can get unwieldy, especially for larger UIs. This is where JSX comes in.

Introducing JSX: The Cleaner Syntax

JSX is a syntax extension that looks like HTML but works within JavaScript. It allows us to write cleaner code by avoiding the cumbersome structure of React.createElement. Instead of creating elements manually, we can write:

const parent = (
  <div id="parent">
    <div id="child">
      <h1>I am an H1 Tag</h1>
      <div id="child2">
        <h2>I am an H2 Tag</h2>
      </div>
    </div>
  </div>
);
Enter fullscreen mode Exit fullscreen mode

React Components: The True Power

React becomes even more powerful when we start using components. Components allow us to encapsulate parts of the UI into reusable, independent pieces of code. They can be written as functions or classes.

function MyComponent() {
  return (
    <div>
      <h1>Hello World from MyComponent</h1>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

Components can be reused and composed to create complex UIs in a maintainable way, making React a powerful tool for modern web development.

Conclusion

React abstracts away much of the complexity of DOM manipulation, allowing developers to focus on building user interfaces rather than worrying about the intricacies of managing HTML elements. With the help of tools like React.createElement, JSX, and components, React makes it easier to build large, scalable applications.

. . . . .
Terabox Video Player