How React Works Under the Hood?
Zipy team
Posted on December 20, 2023
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.
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 does React work under the hood
React operates by utilizing virtual DOM, which acts as a copy of the real DOM (Document Object Model) and reflects the layout and content of a webpage.
By leveraging the DOM, React efficiently updates the altered components of the user interface without requiring complete page re-rendering. This unique approach contributes to React’s speed and efficiency in comparison to frameworks. Now, let’s truly understand what virtual DOM is, and how React virtual DOM works.
What is virtual DOM
The concept of virtual DOM is aimed at enhancing the performance and efficiency of web applications that utilize frameworks like React. Understanding the virtual DOM is crucial to grasp how React under the hood works. Essentially, the virtual DOM acts as a replica of the DOM, which represents the visual structure of a webpage. By utilizing virtual DOM, a key aspect of how React works, you can make changes to the user interface elements without impacting the DOM, which can be time-consuming and resource-intensive.
The primary objective behind virtual DOM, integral to understanding how React works, is to leverage an algorithm that compares any modifications between the current version of virtual DOM and its previous state. Only the necessary updates, a process central to how React works, are then applied to the DOM. This method highlights how React works to optimize UI updates and minimize direct manipulation of the DOM, thereby enhancing app performance and user experience.
How does React virtual DOM work
Let’s first start with the most common term you hear when reading about React. Virtual DOM.
As the name suggests, Virtual DOM is not an actual DOM, but a representation of actual DOM which is kept in memory. It’s a representation of DOM nodes in a tree format which is just a plain JavaScript Object.
Let’s take an example of any JSX that you might find in the return statement of a React component.
<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 traverses the JSX recursively from the parent element. In this case, the parent is a
element. You can see here that the children are defined in the props property of an element. This element has two children, and . element in turn has a text element (”Want to learn about Virtual DOM?”) which gets defined as a child to in the tree structure. And this is how the DOM is converted to a Virtual DOM with nested elements.
in the tree structure. And this is how the DOM is converted to a Virtual DOM with nested elements.
The type defined in the Virtual DOM, in general, refers to the type of HTML DOM element. If you have noticed in the example above, we have used a React Component . Now, this is not a conventional HTML element. Hence, React treats these components a little differently. If it’s a functional component, React directly calls the function with its assigned props and if it’s a class component, React creates a new instance of the class component and calls its render method.
The key and ref properties are the same props that you know are used in components. key is required while rendering a list of elements, which we will see later in the article and ref are the references we pass in any HTML DOM element to manipulate the element like for managing focus. You can learn more about refs here.
This is what a virtual DOM is in a broader sense. Every time a React component updates, React builds a new tree in memory. Creating javascript objects in memory on every update is much faster than updating the actual DOM since DOM operations are expensive to perform.
Now, let’s look at how React js works internally in making the UI re-rendering smoother, faster and with no extra development effort.
How React works
Understanding how React works is pivotal in leveraging React’s full potential in web development. At its core, how React works revolves around rendering and updating the UI in the most efficient way possible. React's design philosophy ensures that it reacts swiftly to user interactions and data changes, making it a go-to choice for dynamic web applications.
Central to how React under the hood works is the concept of components. Components are the building blocks of a React application, encapsulating both logic and presentation. This modular approach exemplifies how React works to create reusable, manageable, and testable UI pieces. By isolating components, React simplifies the development process, embodying how React works to streamline web application development.
Moreover, how React works with state and props facilitates a seamless data flow and reactivity in applications. The state in React helps in managing the data within components, while props allow data to be passed between components. This is quintessential to understanding how React works—it’s not just about the UI, but also about efficiently managing data and state.
The brilliance of how React works also shines in its lifecycle methods. These methods provide hooks at various stages of a component's life, from mounting to updating and unmounting. This aspect of how React works offers developers control over the behavior of components throughout their lifecycle.
In conclusion, the essence of how React works lies in its innovative approach to building user interfaces. By understanding how React works, developers can craft efficient, responsive, and user-friendly web applications. This understanding is not just beneficial but essential for any developer looking 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:
- Two elements of different types will produce different trees.
- 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.
- Apples
- Oranges
- Banana
- Watermelon
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) => (
))
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.
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 as an extension that allows developers to write HTML code within React components. By utilizing a DOM, React updates the parts of the user interface that have changed instead of re-rendering the entire page. This is a core part of how React works to ensure efficiency and performance.
On the other hand, Vue is renowned for its streamlined nature, flexibility, and impressive capabilities. It follows a component-based architecture, which greatly simplifies the creation of user interfaces. While Vue primarily uses HTML templates, it also offers support for JSX as an option. This flexibility in Vue's design contrasts with how React works, emphasizing JSX.
Additionally, Vue features a two-way data binding system that effortlessly keeps your data in sync with the user interface. Vue lifecycle hooks are special functions that allow you to execute your own code at specific stages of a Vue component’s life, such as creation, mounting, updating, and destruction.
Understanding how React works and Vue’s methodologies offers insight into their respective approaches to building responsive and efficient web applications. As you delve deeper into the nuances of React and Vue, the choice of which to use becomes clearer, guided by the specific needs of your project and your preference in development style.
In conclusion, whether you choose React, with its unique approach to UI updates and how React works with JSX, or Vue, with its simplicity and flexibility, depends largely on your project requirements and personal coding style. Both frameworks offer robust solutions for developing dynamic web applications, but understanding their inner workings can greatly influence your choice.
React 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.
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!
Posted on December 20, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 30, 2024
November 30, 2024