How React Works Under the Hood?

Shantanu Patil
6 min read | Published on : Sep 03, 2024
Last Updated on : Sep 03, 2024





how react works under the hood - illustration
Table of Contents

I still remember being a newbie to this world of frontend engineering and learning React. I was impressed with the ease with which I could build web apps using reusable components and JSX. It was amazing how fast React could update the UI. A good advice to all the beginners, understand all javascript concepts before learning React.

Continuing, with React…

I never really paid much attention to how React under the hood works, or what the most common term when it comes to React i.e. Virtual DOM, actually means. I never really felt the need to understand how React under the hood works, as it was getting my job done seamlessly.

In my research on solving the performance issues, I started reading about the functionalities and algorithms that React uses under the hood and that really helped me in solving the problem. The working of components, DOM updates, renderings can only be seen after you deploy your React app on a system.

If you are a new developer just starting with React or just a curious person keen on understanding how React works, then this article is for you. Let’s get started.

How react works - Understanding essentials of React js

To effectively build user interfaces with React it is crucial to understand and master the core concepts and skills of React. It is a javascript library empowers you to develop components of rendering dynamic data and managing user interactions. You can even use bootstrap in react to create beautiful interfaces for better visually appealing experience.

Here are some key elements to grasp when working with React:

  • Components: React applications are built using components which're self contained units of code that define the appearance and behavior of parts of the user interface. These components can be combined to create UI designs. With the help of React UI libraries, you can create beautiful interactive interfaces. React community has provided React libraries to test components in the app, making it easier for developers to write and run tests efficiently.
  • State: State is a way of storing data that can change over time in your component. State is managed by the component itself, and it can be updated by using the setState() method or the useState() hook.
  • Props: Props are short for properties, and they are used to pass data from one component to another. Props are read-only, which means they cannot be modified by the component that receives them.
  • Lifecycle methods: Lifecycle methods are special functions that are called at different stages of a component’s existence. They are used to perform actions such as fetching data, updating state, cleaning up resources, or performing side effects.

What is JSX

JSX serves as a syntax extension for javascript enabling the creation of HTML code within React. JSX, short for JavaScript XML, uses XML tags to define the user interface. Although JSX is not required to use React, it makes it easier to create and read React elements.

JSX has these advantages over plain javascript:

  • It is more concise and readable than using React.createElement() or document.createElement() methods.
  • It can embed javascript expressions inside curly braces { } to dynamically render data or logic.
  • It can use custom components or HTML attributes to customize the appearance and behavior of the elements.
  • It follows XML rules, which means it requires closing tags and proper nesting of elements.

How React works and Functions Behind the Scenes

React uses a system called the virtual DOM, which is a simplified version of the real DOM (Document Object Model). This virtual DOM mirrors the structure and content of a webpage. React's efficient update mechanism uses this virtual DOM to only change the parts of the user interface that need updating, rather than re-rendering the whole page. This method makes React faster and more efficient than other frameworks.

To truly understand how React works, it's essential to grasp the concept of the virtual DOM and how it operates.

Understanding the Virtual DOM

The virtual DOM is a key component in improving the performance of web applications built with frameworks like React. It acts as a copy of the actual DOM, representing the visual structure of a webpage. By using the virtual DOM, React can update the user interface elements without directly affecting the real DOM, which is usually a slow and resource-heavy process.

The main goal of the virtual DOM is to enhance React’s efficiency. It employs an algorithm to compare changes between the current and previous versions of the virtual DOM. Only the necessary updates are then applied to the real DOM. This technique helps React optimize UI updates and reduces the need for direct DOM manipulation, boosting the performance and user experience of the application.

How the React Virtual DOM Works

Let's dive into the term you’ll often encounter in React discussions: the virtual DOM.

As its name suggests, the virtual DOM isn't a real DOM but a representation of it, stored in memory. This representation is organized in a tree structure using simple JavaScript objects.

For example, consider any JSX code you might see in the return statement of a React component. This JSX is translated into a structure that the virtual DOM uses to keep track of changes and efficiently update the real DOM as needed.

<div>
    <h1 className="title">Want to learn about Virtual DOM?</h1>
    <div className="button-container">
        <Button title="Yes" />
	<Button title="No" />
    </div>
</div>

This JSX gets converted into a tree format like this.

{
    type: 'div',
    key: null,
    ref: null,
    props: {
        children: [
            {
                type: 'h1',
                key: null,
                ref: null,
                props: {
                    className: 'title',
                    children: 'Want to learn about Virtual DOM?'
                }
            },
            {
                type: 'div',
                key: null,
                ref: null,
                props: {
                    className: 'button-container',
                    children: [
                        {
                            type: Button(),
                            props: {
                                title: 'Yes'
                            }
                        },
                        {
                            type: Button(),
                            props: {
                                title: 'No'
                            }  
                        }
                    ]
                }
            }
        ]
    }
}

React starts by examining the JSX code recursively, beginning with the parent element. In this example, the parent is a <div> element. The child elements are specified in the props property of each element. This <div> has two children: <h1> and another <div>. The <h1> element contains a text element ("Want to learn about Virtual DOM?"), which is treated as a child of <h1> in the tree structure. This process is how the real DOM is translated into a virtual DOM with nested elements.

The type specified in the virtual DOM generally corresponds to the type of HTML DOM element. For instance, in the example above, we use a React component <Button />, which isn’t a standard HTML element. React handles these components differently. If it's a functional component, React directly calls the function with its assigned props. For a class component, React creates a new instance of the class and calls its render method.

The key and ref properties are the same props you use in components. The key property is essential when rendering a list of elements, which we'll discuss later. The ref property allows you to reference any HTML DOM element for tasks like managing focus. You can learn more about refs in React documentation.

This explanation gives you a broad understanding of the virtual DOM. Every time a React component updates, React constructs a new tree in memory. Creating JavaScript objects in memory during each update is much faster than making changes to the actual DOM, as DOM operations are costly in terms of performance.

Now, let’s explore how React functions internally to make UI re-rendering smoother and faster, without requiring extra development effort. React's efficient handling of updates and its use of the virtual DOM play a crucial role in optimizing performance and enhancing the user experience.

Monitor how your React app for errors and performance with Zipy! Also resolve errors faster.

Try for free

How React works

Knowing how React operates is crucial for using its full potential in web development. The core idea behind React is to render and update the user interface (UI) as efficiently as possible. React's design ensures quick responses to user interactions and data changes, making it a popular choice for dynamic web applications.

Central to React’s functionality is the concept of components. Components are the building blocks of a React application, combining both logic and presentation. This modular approach allows developers to create reusable, manageable, and testable UI elements. By isolating components, React simplifies the development process, making it easier to build web applications.

React also excels in handling state and props, which are key to managing data flow and reactivity in applications. The state is used to manage data within components, while props are used to pass data between components. This efficient data management is fundamental to how React works, ensuring that the UI is not only visually appealing but also dynamically responsive.

React’s lifecycle methods are another crucial aspect. These methods provide hooks at different stages of a component's life, from mounting to updating and unmounting. This feature gives developers control over how components behave throughout their lifecycle, adding another layer of efficiency and customization.

In summary, the essence of React lies in its innovative approach to building user interfaces. Understanding how React works allows developers to create efficient, responsive, and user-friendly web applications. This knowledge is not just useful but essential for any developer aiming to excel in modern web development with React.

React reconciliation

After every component update, React creates a new virtual DOM tree. It then compares the old tree with the new tree to register all the changes that need to be done to the real DOM. This process of generating a new tree and comparing is called reconciliation.

React uses a diffing algorithm to compare both trees to effectively update the UI in a minimum number of operations. This algorithm is quite complex but it is based on two assumptions:

  1. Two elements of different types will produce different trees.

  2. The developer can hint at which child elements may be stable across different renders with a key prop.

Let’s understand what this means.

Two elements of different types will produce different trees

React parses the tree using Breadth-first search (BFS). Whenever a node in a tree is changed, it destroys all the child nodes and reconstructs the tree.

<nav>
    <Component />
</nav>

If the above JSX changes to

<div>
    <Component />
</div>

React will destroy the Component and will construct a new tree. The Component will be unmounted and all of its states will be destroyed. A developer can be careful while building the components so as to avoid unnecessary destroying and reconstructing of components.

While comparing elements of the same type for eg.

<ul>
     <li>Apples</li>
     <li>Oranges</li>
     <li>Banana</li>
</ul>

It just updates the className attribute in the node, instead of destroying and reconstructing the whole node. This doesn't result in un-mounting of component.

The developer can hint at which child elements may be stable across different renders with a key prop.

We come across lists in our React app quite often. It doesn’t have to be an HTML list element. List basically means mapping an array to render the elements. let’s take an example.

<ul>
     <li>Apples</li>
     <li>Oranges</li>
     <li>Banana</li>
</ul>

Now in the next update we add a new element to the list.

<ul>
     <li>Apples</li>
     <li>Oranges</li>
     <li>Banana</li>
     <li>Watermelon</li>
</ul>

React will traverse through the list and check every element. It will check the first element Apples, it is same in both the trees so it doesn't need to update this. This will go on until it finds a new element at the end of the list, watermelon. It will just append the new element to the list. This sounds straightforward.

Now what if we add the new element at the top of the list instead of at the bottom.

<ul>
     <li>Apples</li>
     <li>Oranges</li>
     <li>Banana</li>
     <li>Watermelon</li>
</ul>

React will traverse through the list and check that the first element is changed from Apples to Watermelon. It will reconstruct that element. The second element also changed from Oranges to Apples. React will again reconstruct the element. In the end it will end up reconstructing the whole list. Now, this becomes very expensive when the list size is in 1000s and the updates are happening every second.

To solve this problem keys are introduced.

<ul>
     <li key="apple">Apples</li>
     <li key="orange">Oranges</li>
     <li key="banana">Banana</li>
</ul>

<ul>
     <li key="watermelon">Watermelon</li>
     <li key="apple">Apples</li>
     <li key="orange">Oranges</li>
     <li key="banana">Banana</li>
</ul>

React will now compare the keys and update the element whose keys are modified.

That's the reason we see a warning to provide keys to list items that React throws.

The mistake people do and which I also have been guilty of doing for very long is providing the index of the array as a key.

list.map((item, index) => (
    <li key={index}>{item}</li>
))

This is not a good practice as it may cause displaying of wrong data or performance issues.

After registering what all needs to be updated, React syncs the virtual DOM with the real DOM, and that’s how we see the UI getting updated. To make your website respond better, try using material UI in React. It's a great way to improve how your site behaves and looks.

Monitor react errors and resolve them faster with advanced devtools. Try Zipy!

Start free trial

Advantages of React js

React is known for its easy-to-learn framework for building user interfaces. This simplicity is a fundamental part of how React works, making it simpler to create and understand React elements while also enabling the rendering of data or logic using javascript expressions enclosed in braces { }. Here are some of its advantages:

  • Performance-wise, React is highly efficient: This efficiency is a direct result of how React works with the Virtual DOM and its reconciliation process.
  • React promotes composability and reusability: Its component-based approach, integral to how React works, lets you break down your user interface into reusable pieces of code.
  • Declarative programming is another feature of React: By emphasizing code writing, React allows you to focus on describing what you want to display on screen rather than getting caught up in implementation details. This is a clear illustration of how React works to streamline development.
  • For search engine optimization (SEO) and platform compatibility: React can be utilized with Node.js to render pages on the server side, making it possible to generate HTML pages that are easily indexed by search engines. This flexibility also showcases how React works for enhanced SEO.
  • Rich source of libraries - Developers have made many helpful libraries for React, such as React libraries for UI, React charting libraries, React testing libraries, etc. Moreover, to keep up with the trend of machine learning, many javascript machine learning libraries are also developed reflecting how React works with various advancements.
  • Ease of testing - One of the benefits of using React is that it makes testing easier. It allows to write unit tests for your components,which aligns with how React works as it eases the process by creating small and isolated pieces of code that perform a specific function.

These are a few of the benefits of React that contribute to its adoption, among startups and Fortune 500 companies. Understanding how React works is crucial for anyone interested in gaining knowledge about this powerful framework. If you're interested in deepening your understanding of React, the above-suggested blogs are worth exploring.

Comparing Reactjs with Vuejs

React and Vue are two widely used JavaScript technologies that developers often turn to when building web applications with dynamic user interfaces. Each of these frameworks has its strengths and weaknesses, making the decision between them quite challenging. Before making up your mind, it is best to understand the difference between React and Vue.

React uses JSX, an extension that lets developers write HTML code within React components. By leveraging a virtual DOM, React updates only the parts of the user interface that have changed, instead of re-rendering the whole page. This approach is key to how React maintains efficiency and performance.

On the other hand, Vue is known for its streamlined nature, flexibility, and impressive capabilities. It also follows a component-based architecture, which simplifies the creation of user interfaces. While Vue primarily uses HTML templates, it also supports JSX as an option. This flexibility in Vue’s design stands in contrast to React’s emphasis on JSX.

Vue also features a two-way data binding system, which keeps data and the user interface in sync effortlessly. Vue’s lifecycle hooks are special functions that allow developers to execute custom code at specific stages of a Vue component’s life, such as creation, mounting, updating, and destruction.

Gaining insight into how React works and Vue’s methodologies helps in understanding their respective approaches to building responsive and efficient web applications. As you explore the details of React and Vue, you will find that the choice between them depends on your project’s specific needs and your preferred development style.

In conclusion, whether you choose React, with its unique approach to UI updates and use of JSX, or Vue, with its simplicity and flexibility, depends largely on your project requirements and personal coding style. Both frameworks provide robust solutions for developing dynamic web applications, but understanding their inner workings can greatly influence your decision.

How React works - monitoring and debugging

As we speak about React, it’s important to understand that work doesn’t stop at development. Monitoring and debugging errors are other important elements to maintaining a high-quality React application. React debugger helps you maintain the functionality of your React app and optimize its performance. This is a crucial aspect of understanding how React works in practical scenarios.

  • Here’s why you need to keep React monitoring and debugging in mind:
  • By monitoring errors in your React app, you can ensure your app is bug-free, doesn’t crash, and functions as planned. This process is integral to how React works seamlessly across different environments.
  • To optimize app performance, speed, and responsiveness by reducing unnecessary re-rendering, memory leaks, network latency, etc. These optimizations are a testament to how React works to deliver efficient user experiences.
  • To test and verify your app’s behavior and logic by using breakpoints, watch expressions, call stacks, etc. This helps in gaining a deeper understanding of how React works with various debugging tools.
  • To learn how React works under the hood by exploring the React source code, internals, hooks, etc. This exploration is key to mastering how React works and applying its principles effectively.
  • In conclusion, monitoring and debugging are pivotal in understanding how React works and ensuring the robustness of your application. These practices not only improve the quality of your React applications but also deepen your understanding of the framework’s core mechanisms. By embracing these aspects, developers can create more efficient, reliable, and high-performing React applications, fully leveraging how React works to their advantage.

monitoring and debugging play a vital role in ensuring the smooth operation and performance of applications. But what truly empowers developers in this struggle are the right tools. There is an array of specialized tools designed for React monitoring and debugging that can significantly enhance your workflow. These tools not only simplify the process of tracking down errors but also provide valuable insights into how React works in real-time scenarios. For a comprehensive look at some of the best tools available for website monitoring, including those suitable for React applications, be sure to check out this insightful blog: Website Monitoring Tools. It's an excellent resource for anyone looking to deepen their understanding of how React works with the help of effective monitoring tools.

Start tracking your React errors and debug them faster with Zipy!

Try for free

Conclusion

Hope the above blog explains how React works under the hood. The Virtual DOM strategy in React, a key part of how React under the hood works, helps applications re-render their UI faster. React has also re-implemented the reconciliation architecture after React version 16 by introducing a new data structure called Fiber. But on a high level, it still follows the same principles, crucial to how React works.

Overall, I think with UI page load performance being very critical in this age, it is important for React developers to understand and appreciate how React works. This knowledge is instrumental in avoiding mistakes while defining and using components. Understanding the working principles of React, essentially how React works, has surely helped me in writing better React components and better code. Hope this article was helpful for all my fellow React developers in understanding how React works.

Till then, Happy Coding!

Wanna try Zipy?

Zipy provides you with full customer visibility without multiple back and forths between Customers, Customer Support and your Engineering teams.

The unified digital experience platform to drive growth with Product Analytics, Error Tracking, and Session Replay in one.

product hunt logo
G2 logoGDPR certificationSOC 2 Type 2
Zipy is GDPR and SOC2 Type II Compliant
© 2024 Zipy Inc. | All rights reserved
with
by folks just like you